douping3891 2014-11-05 06:44
浏览 45
已采纳

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

By using this one line code ob_start('ob_gzhandler'); at the top of the page, the php output was about 11 kb according to Chrome console. When I tried to cache the output with the following code, I found the cached file was saved about 65kb. Is the bigger output size the trade off for caching? Is there any way to compress the cached output further? I have tried adding some htaccess rules for html compression but I don't think that helps.

$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(); 
  • 写回答

1条回答 默认 最新

  • douli4337 2014-11-05 07:10
    关注

    Your cached file was not gziped by the server, try this way:

    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. I would leave this task of compressing to the web server (nginx, apache).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys electronics 2021 R1安装报错,错误代码2,如图
  • ¥30 搭建面包板由NE555N和SN74LS90N组成的计时电路时出了问题
  • ¥15 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误
  • ¥15 openpcdet自制数据集评估bev精度和3d精度相同