Generate HTML from PHP Variables and display source

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>
LVL 3
Computer GuyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
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
Ray PaseurCommented:
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

Computer GuyAuthor Commented:
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.
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Ray PaseurCommented:
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

Computer GuyAuthor Commented:
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?
Ray PaseurCommented:
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.
Computer GuyAuthor Commented:
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?
Ray PaseurCommented:
It should not be necessary to have a pre-existing file.  See: http://php.net/manual/en/function.file-put-contents.php
Ray PaseurCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Computer GuyAuthor Commented:
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!
Ray PaseurCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.