我正试图让一个PHP脚本在访问页面时“在后台”运行。该脚本处理了大约10,000个数据库记录,因此我希望用户能够在脚本处理所有这些记录时看到脚本的进度。我一直在寻找EventSource来做到这一点,但是我遇到了几个问题。
首先,直到代码运行完毕,代码才似乎没有刷新(当前到控制台,最终到页面)。理想情况下,它应在每次记录后刷新。
第二,当PHP到达脚本末尾时,该事件不会停止处理,而是重新运行代码。我的控制台最终多次被输出充满。
JavaScript
<script>
// to-do: on click
var outputEvent = new EventSource("{{ url(['for': 'batch-pull', 'event': eventCode]) }}");
outputEvent.onmessage = function(e) {
console.log(e);
}
// to-do: disconnect
// end on click
</script>
PHP
public function batchPullAction($eventCode) {
$visitorsLink = 'visitors/?limit=1000&event=' . $eventCode;
$visitors = $this->getVisitors($visitorsLink);
header('Content-Type: text/event-stream' . "\n\n");
ob_start();
$countMe = 0;
foreach ($visitors as $visitorCode) {
$countMe++;
$pull = new Pull($eventCode, $visitorCode);
try {
// $log = $pull->process();
echo "event: message\ndata: " . $visitorCode . ' = OK<br>' . "\n\n";
sleep(1);
} catch (N200Exception $e) {
echo $visitorCode . ' = ' . $e->getCode() . ': ' . $e->getMessage();
}
ob_flush();
flush();
if ($countMe == 10) {
break;
}
sleep(1);
}
ob_end_clean();
exit;
}
输出
MessageEvent {isTrusted: true, data: "2fwteo2kfazuq = OK<br>", origin: "http://localhost", lastEventId: "", source: null, …}
MessageEvent {isTrusted: true, data: "0dce1ezp890n4 = OK<br>", origin: "http://localhost", lastEventId: "", source: null, …}
MessageEvent {isTrusted: true, data: "3js6n4yh94nwq = OK<br>", origin: "http://localhost", lastEventId: "", source: null, …}
MessageEvent {isTrusted: true, data: "2lnwisow0rduv = OK<br>", origin: "http://localhost", lastEventId: "", source: null, …}
MessageEvent {isTrusted: true, data: "3f8c0mn2qpi3n = OK<br>", origin: "http://localhost", lastEventId: "", source: null, …}
MessageEvent {isTrusted: true, data: "2pf4212ska7xw = OK<br>", origin: "http://localhost", lastEventId: "", source: null, …}
MessageEvent {isTrusted: true, data: "0zxmoslxata5k = OK<br>", origin: "http://localhost", lastEventId: "", source: null, …}
MessageEvent {isTrusted: true, data: "0s7l95ovsd46m = OK<br>", origin: "http://localhost", lastEventId: "", source: null, …}
MessageEvent {isTrusted: true, data: "1ca6vmyuf2af1 = OK<br>", origin: "http://localhost", lastEventId: "", source: null, …}
MessageEvent {isTrusted: true, data: "009tk67fs3qjj = OK<br>", origin: "http://localhost", lastEventId: "", source: null, …}