'PHP retrieve text/event-stream data

For my DIY project I want to retrieve data from an 3rd party API which returns with the 'text/event-stream' header.

Because the connection doesn't close, I do it with a timeout as shown here:

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

Besides being super hacky, it is slow and it feels bad.

Is it possible to only catch the first data-element (JSON) from an event-stream?

So far I couldn't find any satisfying solution for my problem. Maybe I am lacking the correct vocabulary to search with.

Help very appreciated.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source