0

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 ?

1

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That is this str_pad for and Who Paddington smith 4096 chars ?
@yarek added explanation for that, hopefully this will help you to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.