开发者

Is it possible to print result during loop instantly without javascript?

Here is example of code I'm expecting to print message each second.

set_time_limit(0);

foreach($array as $key => $value)
{
    echo $value;

    sleep(1);
}

I'm wondering is it possible to output results during each step in loop instantly, witho开发者_StackOverflowut waiting until it stops.


yes. you can do it using php's flush mechanism.

for example:

   <?
    ob_implicit_flush(true);
    foreach($array as $key => $value)
{
    echo $value;

    sleep(1);
}
    ?>


That's not really possible since the webserver caches the result. The client may get new data as the output cache fills up and sends a new http packet, but it's not good practice to do it like that, because php scripts also timeout, so the results of such an approach can be ambiguous.

Edit: you can make php clear the cache using php's ob_flush as in ob_flush();. However this still leaves the problem that the script might timeout, so you cannot keep doing this for a very long time.

A much better solution would be to make AJAX calls periodically or use WebSockets to keep a persistent connection to the server, in order to get new data as it comes out.

Edit 2: For WebSockets, it's not that short to post here. Also, it only works in HTTP5, Chrome 8 supports it and probably Firefox 4 and Safari 5 as well. Here is a tutorial of using Websockets with PHP: WebSockets with PHP

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜