5

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?

Email
  • 2,395
  • 3
  • 35
  • 63

5 Answers5

5

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

ToBe
  • 2,667
  • 1
  • 18
  • 30
3

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.

sigy
  • 2,408
  • 1
  • 24
  • 55
2

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();
Jijesh Cherayi
  • 1,111
  • 12
  • 15
1

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.

kasper Taeymans
  • 6,950
  • 5
  • 32
  • 51
-1

PHP sends, as you noticed, all data at once (the moment the script has finished) - you search for something like this http://de1.php.net/manual/de/function.ob-get-contents.php :

<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>
Flixer
  • 938
  • 1
  • 7
  • 20