Home > Backend Development > PHP Tutorial > 为什么这个不是慢慢输出

为什么这个不是慢慢输出

WBOY
Release: 2016-06-06 20:11:45
Original
1061 people have browsed it

为什么这个不是慢慢输出
而是6秒后全部输出

回复内容:

为什么这个不是慢慢输出
而是6秒后全部输出

正常情况下,PHP脚本执行完毕后才会把所有结果返回给浏览器,如果你想提前返回,则需要手动flush推送,比如:

<code>BubbleSort.php
<?php // php -S 127.0.0.1:8080 -t /www
// http://127.0.0.1:8080/BubbleSort.php
header('Content-Type: text/html; charset=utf-8');
ob_start();
$array = array(0,1,2,3,4,5,6,7,8,9);
$size = count($array);
for ($i=0;$i<$size;$i++) {
    print_r($array);
    for ($j=0;$j<$size-1-$i;$j++) {
        if ($array[$j] < $array[$j+1]) {
            $temp = $array[$j];
            $array[$j] = $array[$j+1];
            $array[$j+1] = $temp;
        }
    }
    echo '<br />'.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.</code>
Copy after login

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秒从后台获取一次消息。

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template