PHP缓存HTML

内容开头

$cache_file = "cache/index.html";
// 缓存过期时间(秒)
$cache_time = 3600; // 1 小时
// 如果缓存文件存在且未过期,则直接输出缓存内容
if (file_exists($cache_file) && time() - filemtime($cache_file) < $cache_time) {
    readfile($cache_file);
    exit();
}
// 开启缓冲区
ob_start();

内容结尾

// 获取缓冲区内容并清空缓冲区
$html_content = ob_get_clean();
// 创建缓存目录(如果不存在)
if (!file_exists($cache_dir)) {
    mkdir($cache_dir, 0777, true);
}
// 将 HTML 内容写入缓存文件
file_put_contents($cache_file, $html_content);
// 输出 HTML 内容
echo $html_content;

也可以考虑保存时压缩 HTMl 代码

function compress_html($html) {
    // 删除注释
    $html = preg_replace('/<!--(.|\s)*?-->/', '', $html);
    // 删除换行符、制表符和连续的空格
    $html = preg_replace('/\s+/', ' ', $html);
    // 删除标签之间的空格
    $html = preg_replace('/\s*<\s/', '<', $html);
    $html = preg_replace('/\s*>\s*/', '>', $html);
    return $html;
}