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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵