看看php的ob_start(),它可以緩衝所有輸出並保存。 http://php.net/manual/en/function.ob-start.php
增加: 看http://www.php.net/manual/en/function.ob-start.php#106275您要:)功能 編輯: 這裏,甚至simpeler版本:http://www.php.net/manual/en/function.ob-start.php#88212 :)
這裏是一些簡單而有效的解決辦法:
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"));
?>
您可以用http://php.net/manual/en/function.file-put-contents.php保存的template.php或actualpage.php的內容,一些文件,比如cached.php。然後你可以讓actualpage.php檢查cached.php的日期,如果太舊,讓它做一個新的,或者足夠年輕的時候只需要echo actualpage.php或者重新評估template.php而不重建模板。
後的意見,在這裏緩存模板:
<?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"));
?>
要運行這個你可以直接運行緩存的文件,也可以包括這樣的一個其他的頁面上。像:
<?php
// Variables
$weather = "fine";
include("cachedir/cache.php");
?>
[你有什麼試過](http://mattgemmell.com/2008/12/08/what-have-you-tried/)? – ghoti 2012-04-01 22:25:32
生成這些行將比從緩存存儲中獲取2個密鑰更快。嘗試從數據庫緩存數據,不要浪費時間輸出,這是模板引擎的業務。 – 2012-04-01 22:26:12
此代碼僅用於舉例。真正的代碼非常複雜,需要一些SQL查詢。我嘗試很清楚地表明我的問題。我想知道PHP緩存機制。 – Huseyin 2012-04-01 22:32:04