I have a long-running script and want to use output buffering to send output to the browser periodically.
I'm confused, because I've read a number of questions on here that said to use this:
while (...) {
ob_start();
// echo statements
ob_end_flush();
}
But that didn't work for me. I also tried this:
while (...) {
ob_start();
// echo statements
ob_flush();
flush();
ob_end_flush();
}
But that didn't work either. The only thing that seems to work is this:
while (...) {
ob_end_clean();
ob_start();
// echo statements
ob_flush();
flush();
}
Why do I have to call ob_end_clean()
first in order for output buffering to work?
Probably it depends on the rest of your code.
For me the following code works without a problem:
<?php
header( 'Content-type: text/html; charset=utf-8' );
$x = 1;
while ($x < 10) {
echo $x."<br />";
ob_flush();
flush();
sleep(1);
++$x;
}
You can use ob_implicit_flush()
but it makes you don't need to run flash()
each time you run ob_flush()
so above code can be changed to:
<?php
header( 'Content-type: text/html; charset=utf-8' );
$x = 1;
ob_implicit_flush(true);
while ($x < 10) {
echo $x."<br />";
ob_flush();
sleep(1);
++$x;
}
You should also look at your header()
. If in any of above codes I remove/comment line with header all the content will be displayed after scripts ends execution. Output buffering won't work as expected