内容开头
1$cache_file = "cache/index.html";
2// 缓存过期时间(秒)
3$cache_time = 3600; // 1 小时
4// 如果缓存文件存在且未过期,则直接输出缓存内容
5if (file_exists($cache_file) && time() - filemtime($cache_file) < $cache_time) {
6 readfile($cache_file);
7 exit();
8}
9// 开启缓冲区
10ob_start();
内容结尾
1// 获取缓冲区内容并清空缓冲区
2$html_content = ob_get_clean();
3// 创建缓存目录(如果不存在)
4if (!file_exists($cache_dir)) {
5 mkdir($cache_dir, 0777, true);
6}
7// 将 HTML 内容写入缓存文件
8file_put_contents($cache_file, $html_content);
9// 输出 HTML 内容
10echo $html_content;
也可以考虑保存时压缩 HTMl 代码
1function compress_html($html) {
2 // 删除注释
3 $html = preg_replace('/<!--(.|\s)*?-->/', '', $html);
4 // 删除换行符、制表符和连续的空格
5 $html = preg_replace('/\s+/', ' ', $html);
6 // 删除标签之间的空格
7 $html = preg_replace('/\s*<\s/', '<', $html);
8 $html = preg_replace('/\s*>\s*/', '>', $html);
9 return $html;
10}