dongliyi967823 2018-03-22 23:25
浏览 56

在foreach循环中的每次迭代后PHP回显

I'm trying to echo after every iteration of a foreach loop in PHP. The echos aren't rendering until they are all done. I've tried the suggestions from various posts but none are working. Some of my code is:

echo $epTitle . "<br>";
echo "<div>" . '<img src="' . $imgSrc . '" height="70" width="70">';
echo "<button onclick='grabVid(" . '"' . $pageUrl . '"' ..")'>Grab</button>";

I've tried the following:

flush();

.

flush();
ob_flush();

.

while (ob_get_level() > 0)
ob_end_flush();

.

@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
@ob_end_clean();

and other suggestions from: http://php.net/manual/en/function.flush.php and Echo 'string' while every long loop iteration (flush() not working)

Any suggestions? Thanks.

  • 写回答

1条回答 默认 最新

  • duanhuang1699 2018-03-23 01:01
    关注

    If you're using XHR (AJAX) and want to stream the response, you need to periodically check on it using onprogress. The onreadystatechange event will not fire whilst the response is being received, because the readyState will always be loading and not change until the request has completed.

    Here is a good article on the subject:

    PHP Streaming and Output Buffering explained

    It contains this sample JavaScript for the XHR part:

    xhr = new XMLHttpRequest();
    xhr.open("GET", "response.php", true);
    xhr.onprogress = function(e) {
      alert(e.currentTarget.responseText);
    }
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        console.log("Complete = " + xhr.responseText);
      }
    }
    xhr.send();
    

    (I don't know if there's any reason why the example uses e.currentTarget instead of xhr inside the onprogress event handler - I just copied the example as it is.)

    If you're planning on doing this loop for longer than 30 seconds, your PHP script will probably be killed. You can extend the default time limit but if you're site has many users, you want requests to be short as possible for optimum server availability.

    This means rewriting your loop so that each iteration is a single HTTP request.

    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源