使用PHP输出缓冲区压缩缓存的输出
问题描述:
通过在页面顶部使用这一行代码ob_start('ob_gzhandler');
,根据Chrome控制台,php输出大约为11 kb。当我试图用下面的代码缓存输出时,我发现缓存的文件保存了大约65kb。更大的输出尺寸是否需要缓存?有什么办法可以进一步压缩缓存的输出吗?我曾尝试为html压缩添加一些htaccess规则,但我不认为这有帮助。使用PHP输出缓冲区压缩缓存的输出
$id = $_GET["id"];
$cachefile ="cache/p_{$id}.html";
if (file_exists($cachefile)) {
include($cachefile);
echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
exit;
}
ob_start('ob_gzhandler');
$fp = fopen($cachefile, 'w'); // open the cache file for writing
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
fclose($fp); // close the file
ob_end_flush();
答
你的缓存文件不是由服务器gziped,试试这个方法:
ob_start('ob_gzhandler');
$id = $_GET["id"];
$cachefile ="cache/p_{$id}.html";
if (file_exists($cachefile)) {
include($cachefile);
echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))." -->";
} else {
// your html or something else ...
$fp = fopen($cachefile, 'w'); // open the cache file for writing
fwrite($fp, ob_get_contents()); // save the contents of output buffer to the file
fclose($fp); // close the file
}
ob_end_flush();
@ RedGiant:或者保存已压缩的文件,就像你建议的那样。这一切都取决于你的需求。现在,当你有gziped保存的缓存文件时,你必须将编码设置为gzip,以便浏览器知道数据是什么:'if(file_exists($ cachefile)){header('Content-Encoding:gzip'); ...'。 – 2014-11-05 07:53:54