【问题标题】:Contiguous output in CakePHPCakePHP 中的连续输出
【发布时间】:2016-10-15 05:26:58
【问题描述】:

我在循环中有一些长时间的处理,并希望连续输出进度。

while (true)
{
   $percents = $do_my_stuff();
   echo $percents;
   $this->log($percents);
}

我尝试了很多技巧,但仍然没有运气

ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', false);
while (@ob_end_flush());
ini_set('implicit_flush', true);
ob_implicit_flush(true);

flush() 在每个循环中

循环进入

$this->response->body(function () { /* loop with echo here */ }

但脚本完成后浏览器仍会显示所有数据一次。响应头:

HTTP/1.1 200 OK
Host: localhost:8765
Connection: close
X-Powered-By: PHP/5.6.20
Content-type: text/html; charset=UTF-8

PHP 5.6,使用./bin/cake server 的内置服务器,CakePHP 3

我该怎么做?我希望我的用户看到操作的百分比,因为它可以运行很长时间。

【问题讨论】:

    标签: php cakephp stream cakephp-3.x


    【解决方案1】:

    无法强制在浏览器中显示连续输出。某些浏览器在收到结束 </html> 标记之前不会呈现。因此,要验证输出是否正常工作,您需要使用网络监视器查看服务器是否正在流式传输数据。

    另外,不要使用 Cake 的响应对象。这用于缓冲输出并在发送到客户端之前由事件处理。您需要手动发送数据并结束响应。

    header("Content-Type: text/plain");
    while (@ob_end_flush()); // Flush and disable output buffers
    for($a = 0; $a < 100; $a++) {
        echo "X";
        flush(); // Flush output
        sleep(1);
    }
    die; // end request here.
    

    如果您想在客户端显示长任务的进度条。这不是这样做的方法。

    您应该将进度写入会话,保存它,然后通过 AJAX 请求该进度是什么。

    【讨论】:

    • 谢谢。我想显示长时间运行的控制台任务的控制台输出,所以它通常是“进度”,而不是进度条。现在我最终将输出写入文件并通过 AJAX 读取文件内容,但我对这样的解决方案不满意。
    • @Yaroslav 您可以尝试使用passthru 流式传输日志文件的尾部。这是一个要点:gist.github.com/lorenzos/5cbf78a4447e1a98b59f
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    相关资源
    最近更新 更多