PHP在实时输出时出错


PHP Error while outputing in real time

header( 'Content-type: text/html; charset=utf-8' );
echo 'Begin ...<br />';
ob_start();
for( $i = 0 ; $i < 10 ; $i++ )
{
    echo $i . '<br />';
    flush();
    ob_flush();
    sleep(1);
}

为什么这些代码不是每秒输出$i ?它在10秒后输出

在我看来,你的代码,确实,输出$i在每1秒稳定地从终端运行,但它不这样做时,通过web加载。

您的解决方案是启用隐式刷新:http://php.net/manual/en/function.ob-implicit-flush.php

移除ob_start()调用。下面的代码可以很好地工作:

<?php
    header( 'Content-type: text/html; charset=utf-8' );
    echo 'Begin ...<br />';
    ob_implicit_flush (1);
    for( $i = 0 ; $i < 10 ; $i++ )
    {
        echo $i . '<br />';
        flush();
        ob_flush();
        sleep(1);
    }
?>