PHP loop; how to print each result and delay it for a second before echoing another result?

和自甴很熟 提交于 2019-11-26 18:36:26

问题


this is my first question here on stackoverflow, I just curious.. is it possible to delay loop in PHP ? I'm trying to print each result to browser and pause the script using sleep() before it process another loop, but it's not working, here's the script that I use:

<?php
$n = 1;

while ($n < 10) {
    echo $n."<br />";
    $n++;
    sleep(1);
}
?>

PS: I'm using Firefox and Apache2 on Linux Mint.


回答1:


Servers usually buffer the output of a server side script until there's enough in it to output try something like this. Combination of setting output buffering off and manually flushing the buffer. Note the implcit flush line and the flush and ob_flush lines.

<?php 
@ini_set("output_buffering", "Off");
@ini_set('implicit_flush', 1);
@ini_set('zlib.output_compression', 0);
@ini_set('max_execution_time',1200);


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


echo "Testing time out in seconds\n";
for ($i = 0; $i < 1150; $i++) {
    echo $i." -- ";

    if(sleep(1)!=0)
    {
        echo "sleep failed script terminating"; 
        break;
    }
    flush();
    ob_flush();
}

?>



回答2:


PHP executes and renders its output completely before the page renders its content. So no, you can't delay the PHP loop like you want.

You could and should do this with javascript. If you need information from the server printed on delay like this, you can use AJAX to pull the information from the server as it becomes available.



来源:https://stackoverflow.com/questions/15036232/php-loop-how-to-print-each-result-and-delay-it-for-a-second-before-echoing-anot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!