views:

281

answers:

4

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.

+2  A: 

Call flush() after printing.

Ignacio Vazquez-Abrams
+1  A: 

You need to use flush()

leChuck
A: 

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

fastcodejava
+4  A: 

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.

animuson
+1 for providing a good explanation.
GSto