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);
}
why these code is not output $i each second? it output on 10 second later
It seems to me that your code is, indeed, outputing $i in every 1 second steadily when ran from the terminal but it doesn't do it when load through web.
The workaround for you is to enable implicit flushing: http://php.net/manual/en/function.ob-implicit-flush.php
And remove that ob_start()
call. The following code works perfectly:
<?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);
}
?>
It actually does output $i
at each second, but as you are on server-side (using PHP), the page will only be loaded once the whole PHP has already been executed.
If you want the page to output each index i
each second, you should do that in javascript.