现在将数据发送到客户端,并继续PHP处理


Send data to the client now, and continue PHP processing

在PHP中,是否可以立即将数据发送到客户端,并继续PHP处理(可能是阻塞)?

<?php
// some code 
echo json_encode(array('ok' => '1'));  // the client is waiting for this AJAX answer !!
// how to send the response right now before finishing this PHP file ?
// the output is REALLY finished here, so client, you can work with it
some_blocking_processing();  // this is just some server processing that would
                             // block the client for ~ 5 seconds
                             // but it produces no output useful for client
?>

我知道正确的方法可能是使用队列或其他进程来执行处理。

但是,作为一个通用问题,是否可以在PHP文件的中间将数据发送到客户端

这实际上取决于some_blocking_processing()实际在做什么。如果不知道那里发生了什么,我就无法想出解决方案。

不过,我可以向你指出一些你可以做更多研究的领域。其中一个可能是适合您的解决方案:

  1. PHP线程
  2. 生成异步php进程
  3. 将您的状态记录在文件/db中,然后通过cron作业进行额外处理