Considering a simple script
<?php
echo "hi";
foreach ($_GET['arr'] as $a)
{
echo $a ."<br>";
}
echo "<p>Masel tov</p>";
foreach ($_GET['arr2'] as $a)
{
echo $a ."<br>";
}
i expect the script to echo continuously. Instead the script does echo all-at-once when finished. Even the first "hi
" gets echoed after 1 minute when the script finishes.
Is there a setting to prevent this from happen or why is that so?
Depending on your config, output is cached until completion. You can force a flush with either ob_flush()
or flush()
. Sadly many modern browser also dont update until page load is complete, no matter how often you flush.
Configuration Settings for PHP's output buffering. http://www.php.net/manual/en/outcontrol.configuration.php
There is a function ob_implicit_flush that can be used to enable/disable automatic flushing after each output call. But have a look at the comments on the PHP manual before using it.
If you want displaying the items one by one and keep clean code that works with every server setup, you might consider using ajax. I don't like flushing the buffer unless there are no other options to accomplish the task.
If your project isn't a webproject you might consider running your code in the php console (command line) to receive immediate output.
Check with this
if (ob_get_level() == 0)
{
ob_start();
}
for ($i = 1; $i<=10; $i++){
echo "<br> Task {$i} processing ";
ob_flush();
flush();
sleep(1);
}
echo "<br /> All tasks finished";
ob_end_flush();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With