Reputation: 63649
I have a PHP script that takes a few minutes to finish processing. While the page is still loading, I want to show part of the PHP output as it becomes available, which can be done using ob_start()
and ob_flush()
.
After the entire script has finish executing, I want to save all the PHP output right from the start into a HTML file. This can be done using ob_start()
and file_put_contents("log.html", ob_get_contents());
Problem: However, because we are calling ob_flush()
along the way, the final file that gets saved with file_put_contents()
appears to be separated into different files. I suspect this has to do with the buffer being cleared by the ob_start()
calls before file_put_contents()
is called, but why did it not just save the output between the final ob_flush()
and file_put_contents()
to the file, but instead saves several different files? (I may be wrong, the seperate partial files may be due to partial execution of the script)
In other words, how do I show PHP output as a long script executes, and still save all the PHP output to a single HTML file?
PHP Code
// Start the buffering
ob_start();
......
ob_flush();
......
ob_flush();
......
file_put_contents("log.html", ob_get_contents());
Upvotes: 1
Views: 841
Reputation: 2262
You can grab the buffer contents, and store it in a a variable by calling ob_get_contents.
Have you read the manual?
Upvotes: 1
Reputation: 9547
Couple of ways I can think of:
Keep a variable (called something like $content), and append the current buffer every time you call ob_flush():
$content = '';
...
$content .= ob_get_contents();
ob_flush();
...
$content .= ob_get_contents();
ob_flush();
...
file_put_contents('log.html', $content . ob_get_contents());
ob_flush();
Use fopen():
$fp = fopen('log.html', 'w+');
...
fwrite($fp, ob_get_contents());
ob_flush();
...
fwrite($fp, ob_get_contents());
ob_flush();
...
fwrite($fp, ob_get_contents());
fclose($fp);
ob_flush();
Upvotes: 3
Reputation: 23103
You could also use ob_get_contents()
along the way, save it to a variable and then into the file and the outputstream...
Upvotes: 2