yarek
yarek

Reputation: 12034

PHP: How to progressively output inside a loop?

I have a loop and each iteration takes N seconds.

for($i=0;$i<10;$i++) {
 echo $i;
 process(); // 10 seconds process
}

Is there a way to output progressively (in web page) $i without having to wait until the whole loop ends ?

Upvotes: 0

Views: 355

Answers (1)

Shanteshwar Inde
Shanteshwar Inde

Reputation: 1466

Flushes the system write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats.

<?php
  if (ob_get_level() == 0) ob_start();
  for ($i = 0; $i<10; $i++) {
    echo "<br> Line to show.";
    echo str_pad('',4096)."\n";    
    ob_flush();
    flush();
    sleep(2);
  }
  echo "Done.";
  ob_end_flush();
?>

Read documentation here.

EDIT:

str_pad() - Pad a string to a certain length with another string. and Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page. that's why use str_pad() for be safe side.

Upvotes: 5

Related Questions