Why is a PHP script waiting “to finish script” before any echo/output?

孤者浪人 提交于 2021-01-19 01:29:05

问题


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?


回答1:


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.




回答2:


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.

  • flush http://php.net/manual/en/function.flush.php
  • ob_flush http://php.net/manual/en/function.ob-flush.php

Configuration Settings for PHP's output buffering. http://www.php.net/manual/en/outcontrol.configuration.php




回答3:


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.




回答4:


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();



回答5:


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);
?>


来源:https://stackoverflow.com/questions/21583628/why-is-a-php-script-waiting-to-finish-script-before-any-echo-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!