使用PHP输出缓冲区压缩缓存的输出


Compress cached output using PHP output buffers

根据Chrome控制台,通过在页面顶部使用这一行代码ob_start('ob_gzhandler');,php输出约为11kb。当我尝试用下面的代码缓存输出时,我发现缓存的文件保存了大约65kb。更大的输出大小是缓存的折衷方案吗?有没有办法进一步压缩缓存的输出?我试着为html压缩添加一些htaccess规则,但我认为这没有帮助。

$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(); 

服务器没有对缓存的文件进行gzip打包,请尝试以下方式:

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(); 

p.s.我会把压缩的任务留给web服务器(nginx,apache)。