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

时间:2013-12-01 19:39:01

标签: php curl flush output-buffering long-running-processes

我有一个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循环的每次迭代之后,我能做些什么来强制脚本输出echoed / print_r'ed数据?

非常感谢。

2 个答案:

答案 0 :(得分:1)

您需要在循环内移动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();

  }

将输出缓冲区(ob_*)函数视为堆栈上的push和pop。您可以通过将缓冲区推入堆栈(ob_start())来指定要开始记录的位置,然后在要输出时,将缓冲区从堆栈中弹出并对结果执行某些操作(ob_flush()ob_get_*()等)。每个ob_start()必须具有匹配的缓冲区结束函数。

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

答案 1 :(得分:0)

在开始时尝试使用它:

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

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