开发者

echo/print issue in php while loop

开发者 https://www.devze.com 2022-12-22 10:18 出处:网络
I need a fix for this.here is just part of my code <?php $number = 30;开发者_如何转开发 while($number > 0) {

I need a fix for this.

here is just part of my code

<?php
$number = 30;开发者_如何转开发
while($number > 0) {
 $number--;
 sleep(30);
 print "$number . Posted<br>";

}
?> 

The loop process in the loop is actually much bigger, i just put the important stuff.

Anyways as you can see it should print

30 posted

(wait 30 seconds)

29 Posted

(wait 30 seconds)

28 Posted

(wait 30 seconds)

But instead it waits till the loop is over, then just prints it all at once. Is there a fix for this? I was thinking an ajax method, but I dont know of any.


Nice that everyone explained why.

This is because by default PHP will process everything before it 'flushed' anything out to the browser. By just printing each line, it's storing that information in the buffer which will all be printed simultaneously once PHP is finished executing.

If you want PHP to flush that content to the browser immediately after the line, you need to call flush() after each one, then it will output the text one line at a time after each one is called.


Call flush() after printing.


You need to use flush()


An example of a loop with flush() is

<?php
 ob_start();
 for ($i = 0; $i < 10; $i++)
 {
   echo "<div>" . time() . ": Iteration $i</div>";
   sleep(1);
   ob_flush();
   flush();
 } 
 ob_end_flush();
?>

You should not flush often because you force php to process messages and this will increase the time of execution.


You might put \n in echo or print to flush the buffer.

0

精彩评论

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