Solved

Generate HTML from PHP Variables and display source

Posted on 2012-04-04
11
257 Views
Last Modified: 2012-08-13
Hi,

I have some PHP variables on page variable.php

$Date = "4/3/12";
$Number = "32";
$Name = "John Doe";

I have a predefined HTML layout on layout_template.php

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Running Results: <?php echo $Date;?></title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<b><?php echo "On $Date, $Name Came in $Number.";?><b>
</body>
</html>


which will output: On 4/3/12, John Doe Came in 32.

What can I do to put a box below the output with source code, and then have a button to click to save the source as an html page (I don't want to view source and copy/paste?)

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Running Results: 4/3/12</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<b>On 4/3/12, John Doe Came in 32.<b>
</body>
</html>
0
Comment
Question by:Computer Guy
  • 7
  • 4
11 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37807555
This may help get you started...  http://www.laprbass.com/RAY_dynamic_to_static_page.php
<?php // RAY_dynamic_to_static_page.php
error_reporting(E_ALL);

// ASSIGN VALUES TO THE VARIABLES
$Date   = "4/3/12";
$Number = "32";
$Name   = "John Doe";

// CREATE THE HTML PAGE USING HEREDOC NOTATION
$html = <<<HTML
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="iso-8859-1" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<title>Running Results: $Date</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<b>On $Date, $Name Came in $Number<b>
</body>
</html>
HTML;

// CONFIGURE AN HTML URL
$uri = $_SERVER['REQUEST_URI'];
$uri = preg_replace('#^/#', NULL, $uri);
$uri = preg_replace('#\.php#i', '.html', $uri);

// USE OUTPUT BUFFERS TO CAPTURE THE WEB PAGE
ob_start();
echo $html;
$htm = ob_get_contents();

// WRITE THE STATIC VERSION OF THE PAGE
file_put_contents($uri, $htm);

// SHOW THE SOURCE CODE
highlight_file(__FILE__);

Open in new window

I will tinker with it a little more and see what I can come up with..  Cheers, ~Ray
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37807727
See if this is a little closer to what you envision.  I believe you may be able to omit the part about writing the static file to the server.  But this process of dynamic-to-static conversion is very useful if you have, for example, a complicated dynamic page that takes a long time to generate.  You can generate the HTML once and save it on the server.  Then you can use the PHP script to just copy the HTML to the browser output stream.  When the page has "aged" too long, simply delete the HTML page, and let its absence be a signal to the PHP script that it must regenerate the HTML.
http://www.laprbass.com/RAY_temp_audiotech520.php
<?php // RAY_temp_audiotech520.php
error_reporting(E_ALL);

// ASSIGN VALUES TO THE VARIABLES
$Date   = "4/3/12";
$Number = "32";
$Name   = "John Doe";

// CREATE THE HTML PAGE USING HEREDOC NOTATION
$html = <<<HTML
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="iso-8859-1" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<title>Running Results: $Date</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<b>On $Date, $Name Came in $Number<b>
</body>
</html>
HTML;

// CONFIGURE AN HTML URL
$uri = $_SERVER['REQUEST_URI'];
$uri = preg_replace('#^/#', NULL, $uri);
$uri = preg_replace('#\.php#i', '.html', $uri);

// USE OUTPUT BUFFERS TO CAPTURE THE WEB PAGE
ob_start();
echo $html;
$htm = ob_get_contents();

// TERMINATE THE OUTPUT BUFFERS
ob_get_clean();

// WRITE THE STATIC VERSION OF THE PAGE
file_put_contents($uri, $htm);

// WRITE THE HTML TO THE BROWSER
echo $htm;

// COUNT THE NEWLINE CHARACTERS
$linecount = substr_count($htm, PHP_EOL);

// PUT THE HTML INTO A TEXTAREA FOR CLIENT TO COPY
$form = <<<FORM
<br/>
<br/>
HERE IS THE HTML:
<form>
<textarea cols="80" rows="$linecount">$htm</textarea>
</form>
FORM;

echo $form;

Open in new window

0
 
LVL 3

Author Comment

by:Computer Guy
ID: 37807790
Hi,

All looks good.

Though, I want to have a button that will let me download the file to my computer instead of the server.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37807844
I think we can do that - sort of.  See the link added at the bottom.
<?php // RAY_temp_audiotech520.php
error_reporting(E_ALL);

// ASSIGN VALUES TO THE VARIABLES
$Date   = "4/3/12";
$Number = "32";
$Name   = "John Doe";

// CREATE THE HTML PAGE USING HEREDOC NOTATION
$html = <<<HTML
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="iso-8859-1" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<title>Running Results: $Date</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<b>On $Date, $Name Came in $Number<b>
</body>
</html>
HTML;

// CONFIGURE AN HTML URL
$uri = $_SERVER['REQUEST_URI'];
$uri = preg_replace('#^/#', NULL, $uri);
$uri = preg_replace('#\.php#i', '.html', $uri);

// USE OUTPUT BUFFERS TO CAPTURE THE WEB PAGE
ob_start();
echo $html;
$htm = ob_get_contents();

// TERMINATE THE OUTPUT BUFFERS
ob_get_clean();

// WRITE THE STATIC VERSION OF THE PAGE
file_put_contents($uri, $htm);

// WRITE THE HTML TO THE BROWSER
echo $htm;

// COUNT THE NEWLINE CHARACTERS
$linecount = substr_count($htm, PHP_EOL);

// PUT THE HTML INTO A TEXTAREA FOR CLIENT TO COPY
$form = <<<FORM
<br/>
<br/>
HERE IS THE HTML:
<form>
<textarea cols="80" rows="$linecount">$htm</textarea>
</form>
<a target="_blank" href="RAY_force_download_GET.php?u=$uri">Download<a>
FORM;

echo $form;

Open in new window

This is the "force download" script.  Be aware that this is a teaching example only and it is a gaping security hole so I am not going to leave it activated on my server.  When you implement this technology, you will want to add some sanity checks to the script so that it cannot be used to steal information from your server.
<?php // RAY_force_download_GET.php
error_reporting(E_ALL);


// EXAMPLE OF USAGE
// <a target="_blank"
//    href="RAY_force_download_GET.php?u=http://www.google.com/intl/en_ALL/images/logo.gif">Google Logo</a>


// REQUIRED FOR USE WITH THE PHP date() FUNCTIONS
date_default_timezone_set('America/New_York');

// THE NAME OF THE FILE TO DOWNLOAD IS IN THE URL
$url = !empty($_GET["u"]) ? $_GET["u"] : NULL;

// USE CASE
if ($url) force_download($url);



// FUNCTION TO FORCE A DOWNLOAD FROM A FILE
function force_download($filename)
{
    // TRY TO GET THE CONTENTS OF THE FILE
    $filedata = @file_get_contents($filename);

    // SUCCESS
    if ($filedata)
    {
        // GET A NAME FOR THE FILE
        $basename = basename($filename);

        // THESE HEADERS ARE USED ON ALL BROWSERS
        header("Content-Type: application-x/force-download");
        header("Content-Disposition: attachment; filename=$basename");
        header("Content-length: " . (string)(strlen($filedata)));
        header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");

        // THIS HEADER MUST BE OMITTED FOR IE 6+
        if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
        {
            header("Cache-Control: no-cache, must-revalidate");
        }

        // THIS IS THE LAST HEADER
        header("Pragma: no-cache");

        // FLUSH THE HEADERS TO THE BROWSER
        flush();

        // CAPTURE THE FILE IN THE OUTPUT BUFFERS - WILL BE FLUSHED AT SCRIPT END
        ob_start();
        echo $filedata;
    }

    // FAILURE
    else
    {
        die("ERROR: UNABLE TO OPEN $filename");
    }
}

Open in new window

0
 
LVL 3

Author Comment

by:Computer Guy
ID: 37807929
Thanks so much:

2 questions:

I get this error on my URL

Warning: file_put_contents(demo/loop/testsavepage2.html) [function.file-put-contents]: failed to open stream: No such file or directory in /home/test/public_html/demo/loop/testsavepage2.php on line 40

and when I go to download I get this error: 404 Page Cannot Be Found

Was  there anything else I needed to do besides copy and paste your code?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37808060
Beside copy and paste?  Not that I can think of - it may be a file path issue.  It worked as written on my server.  You might try omitting line 28 which is the regular expression that removes the leading slash from the script name.  Or you might try synthesizing a file name from the "basename() of the file.
0
 
LVL 3

Author Comment

by:Computer Guy
ID: 37808180
I see a part of it that I missed.

I see you have 2 seperate files, so I created those.

When I get this error when I load page: RAY_temp_audiotech520.php


Warning: file_put_contents(/demo/loop/audiotech520.html) [function.file-put-contents]: failed to open stream: No such file or directory in /home/djesct/public_html/demo/loop/audiotech520.php on line 40

am I suppose to have a blank audiotech520.html in that folder?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37808428
It should not be necessary to have a pre-existing file.  See: http://php.net/manual/en/function.file-put-contents.php
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 37808463
Maybe try hardcoding a file name, something like this...
<?php // RAY_temp_audiotech520.php
error_reporting(E_ALL);

// ASSIGN VALUES TO THE VARIABLES
$Date   = "4/3/12";
$Number = "32";
$Name   = "John Doe";

// CREATE THE HTML PAGE USING HEREDOC NOTATION
$html = <<<HTML
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="iso-8859-1" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<title>Running Results: $Date</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<b>On $Date, $Name Came in $Number<b>
</body>
</html>
HTML;

// CONFIGURE AN HTML URL
$uri = 'myfile.txt';

// USE OUTPUT BUFFERS TO CAPTURE THE WEB PAGE
ob_start();
echo $html;
$htm = ob_get_contents();

// TERMINATE THE OUTPUT BUFFERS
ob_get_clean();

// WRITE THE STATIC VERSION OF THE PAGE
file_put_contents($uri, $htm);

// WRITE THE HTML TO THE BROWSER
echo $htm;

// COUNT THE NEWLINE CHARACTERS
$linecount = substr_count($htm, PHP_EOL);

// PUT THE HTML INTO A TEXTAREA FOR CLIENT TO COPY
$form = <<<FORM
<br/>
<br/>
HERE IS THE HTML:
<form>
<textarea cols="80" rows="$linecount">$htm</textarea>
</form>
<a target="_blank" href="RAY_force_download_GET.php?u=$uri">Download<a>
FORM;

echo $form;

Open in new window

0
 
LVL 3

Author Comment

by:Computer Guy
ID: 37822821
Hi, One last thing on this, on the audiotech520.php file where I have the assigned variables, $Date, $Number, $Name, I need input those in a form and they can't be static.

Thanks!
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37822948
Has the question changed here?  Do you need help using HTML forms with a PHP action script?  If so, the PHP.net has a good reference in the introductory tutorial.  You will want to read the linked pages, as well as the central tutorial page.
http://us.php.net/manual/en/tutorial.forms.php
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

I've been asked to discuss some of the UX activities that I'm using with my team. Here I will share some details about how we approach UX projects.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now