【问题标题】:PHP output buffer issue when using ob_gzhandler and ob_clean together一起使用 ob_gzhandler 和 ob_clean 时的 PHP 输出缓冲区问题
【发布时间】:2013-12-24 12:18:32
【问题描述】:

我很难找出以下代码中的问题,我真的需要一个解决方案。

考虑以下代码:

<?php
//starting a new output buffer, with a GZIP compression
ob_start("ob_gzhandler");
//this goes into the buffer
echo "Hi";
//grabbing the buffer's content
$content = ob_get_contents();
//cleaning the buffer
ob_clean();
//we're still inside the buffer, show the content again
echo $content;

此代码无法输出“Hi”,而是看到“‹óÈM”,是什么破坏了正确的缓冲?知道一旦我删除“ob_gzhandler”,缓冲是正确的,一切都很好。我不想创建另一个缓冲区并销毁当前缓冲区。我只想使用 ob_clean 清理当前的。

有什么想法吗?提前致谢。

【问题讨论】:

  • 我有正确的输出和你的代码....在我的本地主机上测试过

标签: php output-buffering


【解决方案1】:

谢谢你的回答,我知道为什么了,顺便说一下我的机器上安装了GZIP,就是在设置ob_gzhandler时,缓冲区是逐块压缩的,所以在使用ob_get_contents()时,最后一个chunck的一部分丢失了,我最终得到了奇怪的输出。

要纠正这种行为(或至少绕过它),请打开第二个输出缓冲区,并单独使用 gzhandler()。

像这样

ob_start("ob_gzhandler");
ob_start();

现在第二个没有压缩,我可以用它做任何我想做的事情(因此获取它的内容,清理它等等)。鉴于使用 gzhandler 打开了更高级别的输出缓冲区,内容无论如何都会被压缩。

【讨论】:

  • 为了确保它正常工作,我们可以测试 HTTP 压缩 here
【解决方案2】:

也许您的机器上没有启用/安装 gzip 压缩。

尝试了您的代码并得到了类似的东西。我的机器上没有安装 gzip,试试这个: 这是你的代码,但有一个条件,如果 gzip 没有启动,缓冲区就会启动。

//starting a new output buffer, with a GZIP compression
if (!ob_start("ob_gzhandler")) ob_start();
//this goes into the buffer
echo "Hi";
//grabbing the buffer's content
$content = ob_get_contents();
//cleaning the buffer
ob_clean();
//we're still inside the buffer, show the content again
echo "<pre>"; echo $content; echo "</pre>";
ob_end_flush(); 

如果您收到“Hi”,则可能没有安装 gzip。

【讨论】:

    猜你喜欢
    • 2011-09-18
    • 2014-10-01
    • 2017-10-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多