PHP检索文本/事件流数据



对于我的DIY项目,我想从第三方API检索数据,该API返回'text/event-stream'头。

因为连接没有关闭,所以我会超时,如下所示:

$url='https://example.com/api/';
$ctx = stream_context_create(array('http'=>
array(
'timeout' => 1 // second
)
));
$data = file_get_contents($url, false, $ctx);

除了超级暴躁之外,它还很慢,感觉很糟糕。

是否可以只捕获事件流中的第一个数据元素(JSON(

到目前为止,我找不到任何令人满意的解决方案来解决我的问题。也许我缺少正确的词汇来搜索。

非常感谢您的帮助。

以下代码使我能够读取单个事件。事件流似乎在每个事件之后都有一个双EOL。至少在我的情况下是这样。我不确定是否所有这些流都是这样。

CCD_ 1可以被多次调用以读取一个以上的事件。

$handle = fopen($url, "rb");
function readEvent($handle) {
$line = '';
while (true) {
$byte = fread($handle, 1);
if ($line == '') {
$timeStamp = DateTime::createFromFormat('U.u', microtime(true));
}
if ($byte === "n") {
fread($handle, 1); // skip one empty line (not sure if that is only necessary on the stream I am consuming)
return ['timeStamp' => $timeStamp, 'event' => $line];
}
$line .= $byte;
}
}
$event = readEvent($handle);
echo '1st event: ' . PHP_EOL;
echo '- received: ' . $event['timeStamp']->format("Y-m-d H:i:s.u") . PHP_EOL;
echo '- event: ' . $event['event'] . PHP_EOL;
fclose($handle);

最新更新