时间:2021-07-01 10:21:17 帮助过:1人阅读
而是6秒后全部输出
而是6秒后全部输出
正常情况下,PHP脚本执行完毕后才会把所有结果返回给浏览器,如果你想提前返回,则需要手动flush推送,比如:
BubbleSort.php
'.str_repeat(' ', 1024*4);
ob_flush();
flush();
sleep(1);
}
echo 'Done.';
ob_end_flush();
?>
每隔1秒显示1行:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 )
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 0 )
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 7 [6] => 8 [7] => 9 [8] => 1 [9] => 0 )
Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 6 [4] => 7 [5] => 8 [6] => 9 [7] => 2 [8] => 1 [9] => 0 )
Array ( [0] => 4 [1] => 5 [2] => 6 [3] => 7 [4] => 8 [5] => 9 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 [4] => 9 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
Array ( [0] => 6 [1] => 7 [2] => 8 [3] => 9 [4] => 5 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
Array ( [0] => 7 [1] => 8 [2] => 9 [3] => 6 [4] => 5 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
Array ( [0] => 8 [1] => 9 [2] => 7 [3] => 6 [4] => 5 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
Array ( [0] => 9 [1] => 8 [2] => 7 [3] => 6 [4] => 5 [5] => 4 [6] => 3 [7] => 2 [8] => 1 [9] => 0 )
Done.
PHP_CLI_Server能够实时输出.Apache和Nginx的gzip可能会进行输出缓存,这将导致flush()函数产生的结果不会立即被发送到客户端浏览器.
在Nginx+PHP-FPM下还要注意Nginx的fastcgi buffer,比如:
fastcgi_buffer_size 128k;
fastcgi_buffers 8 128k;
表示Nginx会缓冲PHP-FPM输出的信息,当达到128k时才会将缓冲区的数据发送给客户端,那么我们首先需要将这个缓冲区调小:
fastcgi_buffer_size 4k;
fastcgi_buffers 8 4k;
并且,必须禁用gzip:
gzip off;
然后,在php中,在ob_flush和flush前,输出一段达到4k的内容,例如:
echo str_repeat(' ', 1024*4);
到此,PHP就可以正常通过ob_flush和flush逐行输出需要的内容了.
楼上正解,但你也看到缓冲这类浏览器兼容性问题很多。
既然慢慢输出不如选用js,隔1秒从后台获取一次消息。