<?php
//文件名
$filename="filename.html";
//文件路徑,DIRECTORY_SEPARATOR適合Linux以及Windows
$fileabs = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . $filename;
//查找有沒有緩存文件的存在
if (file_exists($fileabs)) {
//有緩存文件直接調用
include $fileabs;
//獲取當前時間戳
$now_time = time();
//獲取緩存文件時間戳
$last_time = filemtime($fileabs);
//如果緩存文件生成超過指定的時間直接刪除文件
if (($now_time - $last_time) / 60 > 30) {
unlink($fileabs);
}
exit;
}
//開啓緩存
ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!--html內容代碼-->
</body>
</html>
<?php
//在文件代碼末尾獲取上面生成的緩存內容
$content = ob_get_contents();
//寫入到緩存內容到指定的文件夾
$fp = fopen($fileabs, 'w');
fwrite($fp, $content);
fclose($fp);
ob_flush(); //從PHP內存中釋放出來緩存(取出數據)
flush(); //把釋放的數據發送到瀏覽器顯示
ob_end_clean(); //清空緩衝區的內容並關閉這個緩衝區
?>