Look at php's ob_start(), it can buffer all output and save this.
http://php.net/manual/en/function.ob-start.php
Addition:
Look at http://www.php.net/manual/en/function.ob-start.php#106275 for the function you want :)
Edit:
Here a even simpeler version: http://www.php.net/manual/en/function.ob-start.php#88212 :)
Here some simple, but effective, solution:
template.php
<?php
echo '<p>Now is: <?php echo date("l, j F Y, H:i:s"); ?> and the weather is <strong><?php echo $weather; ?></strong></p>';
echo "<p>Template is: " . date("l, j F Y, H:i:s") . "</p>";
sleep(2); // wait for 2 seconds, as you can tell the difference then :-)
?>
actualpage.php
<?php
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
// Variables
$weather = "fine";
// Evaluate the template (do NOT use user input in the template, look at php manual why)
eval("?>" . get_include_contents("template.php"));
?>
You could save the contents of template.php or actualpage.php with http://php.net/manual/en/function.file-put-contents.php to some file, like cached.php. Then you can let the actualpage.php check the date of cached.php and if too old, let it make a new one or if young enough simply echo actualpage.php or re-evaluate template.php without rebuilding the template.
After comments, here to cache the template:
<?php
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
file_put_contents("cachedir/cache.php", get_include_contents("template.php"));
?>
To run this you can run the cached file directly, or you can include this on an other page. Like:
<?php
// Variables
$weather = "fine";
include("cachedir/cache.php");
?>