当前位置:Gxlcms > PHP教程 > 我从PHP官方手册拷贝下来一段关于缓冲的代码,但是执行结果却是错的,求解!

我从PHP官方手册拷贝下来一段关于缓冲的代码,但是执行结果却是错的,求解!

时间:2021-07-01 10:21:17 帮助过:17人阅读

我拷贝代码的地址是:http://fr2.php.com/manual/zh/function.ob-flush.php#109314

我的代码如下,执行后不是逐行显示,而是等了很长时间后,一起出现出来:

header('Content-type:text/html; charset=utf-8');
if (ob_get_level() == 0) ob_start();

for ($i = 0; $i<10; $i++){

    echo "
Line to show."; echo str_pad(' ',4096)."\n"; ob_flush(); flush(); sleep(2); } echo "Done."; ob_end_flush();

OS:Mac osx 10.9
webservice: nginx 1.4
php: 5.6

回复内容:

我拷贝代码的地址是:http://fr2.php.com/manual/zh/function.ob-flush.php#109314

我的代码如下,执行后不是逐行显示,而是等了很长时间后,一起出现出来:

header('Content-type:text/html; charset=utf-8');
if (ob_get_level() == 0) ob_start();

for ($i = 0; $i<10; $i++){

    echo "
Line to show."; echo str_pad(' ',4096)."\n"; ob_flush(); flush(); sleep(2); } echo "Done."; ob_end_flush();

OS:Mac osx 10.9
webservice: nginx 1.4
php: 5.6

运行毫无问题.
Line to show.
Line to show.
Line to show.
Line to show.
Line to show.
Line to show.
Line to show.
Line to show.
Line to show.
Line to show. Done.

PHP版本太高

输出下ob_get_level()函数看是不是为0,是0的话应该是没有开启输出缓冲区。我这的ob_get_level()返回1。

注意flushob_flush的区别:
ob_flush 操作的是php本身的buffer
flush 操作的是 apacheflush,也就是说这个对 nginx是无效果的

nginx下要如下设置试一下:

fastcgi_max_temp_file_size  0  #禁止磁盘缓冲
fastcgi_buffers 1 1k #把buffer设小

编辑 php.ini,设置 output_buffering=0 禁用 buffering 机制,重启服务器试试

人气教程排行