使用长时间运行的PHP脚本间歇性地回显数据


Intermittently echo out data with long-running PHP script

我有一个PHP脚本,它会发出一堆cURL请求。在每个cURL请求之后,我想回显一些数据,但目前,数据只在每5-10个cURL请求后才回显。

我试过使用ob_flushflush,但似乎没有什么区别。以下是我的脚本的基本流程:

<?php
  header('Content-Type: text/html; charset=UTF-8');
  set_time_limit(0);
  ob_start();
  $arr = array(); // Lots of strings in this array
  foreach ($arr as $elem) {
    // Use $elem to make cURL request and return HTML.
    // Run regexes on returned HTML.
    echo '<pre>';
    print_r($matches[1]);
    print_r($matches[2]);
    echo '</pre>';
    ob_flush();
    flush();
  }

我能做些什么来强制脚本在foreach循环的每次迭代后输出回显的/print_r’ed数据吗?

非常感谢。

您需要在循环中移动ob_start(),如:

<?php
  header('Content-Type: text/html; charset=UTF-8');
  set_time_limit(0);
  $arr = array(); // Lots of strings in this array
  foreach ($arr as $elem) {
    ob_start();
    // Use $elem to make cURL request and return HTML.
    // Run regexes on returned HTML.
    echo '<pre>';
    print_r($matches[1]);
    print_r($matches[2]);
    echo '</pre>';
    ob_end_flush();
    flush();
  }

将Output Buffer(ob_*)函数想象为堆栈上的推送和弹出。通过将缓冲区推送到堆栈(ob_start())来指定要开始录制的位置,然后在想要输出时,将缓冲区从堆栈中弹出,并对结果进行处理(ob_flush()ob_get_*()等)。每个ob_start()必须具有匹配的缓冲区结束函数。

您还希望使用ob_end_flush()而不是ob_flush(),因为我认为您不希望在每次运行后保留缓冲区。

尝试在开始时使用这个:

apache_setenv('no-gzip', 1);
ini_set('output_buffering', 0);
ini_set('zlib.output_compression', 0);
ini_set('implicit_flush', 1);

然后做你已经做过的事情。