Skip to content

Core\Http\Stream::events

$stream->events(): Core\Http\Events

Reads the body of a streamed reply as server-sent events, one event at a time.

Server-sent events are a text format for a stream of messages from a server. A server sends one event as a few data, event and id lines, and ends it with a blank line. A foreach over events() gives one Core\Http\Event for each finished event, as soon as it arrives. A line that starts with : is a comment and is skipped.

The body of a stream can be read only once. After events(), a call to events(), lines(), chunks() or saveTo() on the same stream throws a LogicError.

Good to know: an event that the server did not finish before the connection ended is not given to your program. One line may have at most 64 KB, and one event's data at most 1 MB. A longer one throws an error.

The examples below print the data of each event, handle events by their name, and collect the text an AI service sends piece by piece.

Return value

Returns Core\Http\Events. An Iterable<Core\Http\Event> that a foreach can loop over once. An event is complete at the blank line that ends it. A comment line is skipped. A retry line is read and ignored, because your program decides when to reconnect.

Errors

  • LogicErrorThe body of this stream has already been read. A body can be read only once, in one way. The error message names the method that read it.
  • RuntimeErrorA line of the reply is longer than the line limit, or the data of one event is longer than the event limit. It is also thrown when one event is longer than its size limit before its blank line. These limits are fixed, so a server cannot make your program use unlimited memory. It is also thrown when the text is not valid UTF-8, or when the reply's chunked encoding is broken.
  • TimeoutErrorNo data arrived for longer than idle, or the body took longer than its maxDuration.
  • IOErrorThe connection failed while the body was arriving.

Examples

Printing each event

<?nvs
// Shows how to read server-sent events and print the data of each one.
// The reply comes from this table, so nothing is sent over a network.
// Each event ends with a blank line.
Core\Test::answerHttp('https://prices.example.com/live', 200, {
body: "data: apples 1.20\n\ndata: pears 0.95\n\ndata: plums 2.10\n\n",
headers: ['content-type' => 'text/event-stream'],
});
Core\Http\Stream $prices = Core\Http\Client::openStream(Core\Http\Method::Get, 'https://prices.example.com/live');
// This prints three lines, one for each event.
foreach ($prices->events() as Core\Http\Event $event) {
echo $event->data(), "\n";
}
Output
apples 1.20
pears 0.95
plums 2.10

Handling events by name

<?nvs
// Shows how to handle each kind of event in a different way.
// An `event` line gives an event its name. The line starting with `:` is a comment.
Core\Test::answerHttp('https://builds.example.com/job/12', 200, {
body: ": started\n\nevent: step\ndata: compile\n\nevent: step\ndata: test\n\nevent: finished\ndata: ok\n\n",
headers: ['content-type' => 'text/event-stream'],
});
Core\Http\Stream $build = Core\Http\Client::openStream(Core\Http\Method::Get, 'https://builds.example.com/job/12');
foreach ($build->events() as Core\Http\Event $event) {
// `name()` returns `null` for an event without an `event` line.
tainted string $kind = $event->name() ?? 'message';
if ($kind == 'step') {
echo 'running: ', $event->data(), "\n";
} elseif ($kind == 'finished') {
// This prints "result: ok".
echo 'result: ', $event->data(), "\n";
}
}
Output
running: compile
running: test
result: ok

Collecting a streamed answer

<?nvs
// Shows how to collect an answer that an AI service sends in small pieces.
// Many AI services send each new word as one event, and send `[DONE]` at the end.
Core\Test::answerHttp('https://ai.example.com/v1/complete', 200, {
body: "data: The\n\ndata: order\n\ndata: has shipped.\n\ndata: [DONE]\n\n",
headers: ['content-type' => 'text/event-stream'],
});
Core\Http\Stream $reply = Core\Http\Client::openStream(Core\Http\Method::Post, 'https://ai.example.com/v1/complete');
tainted string $answer = '';
foreach ($reply->events() as Core\Http\Event $event) {
if ($event->data() == '[DONE]') {
break;
}
// Each piece is added to the answer. A piece can start with a space.
$answer = $answer . $event->data();
}
// This prints "The order has shipped.".
echo $answer, "\n";
Output
The order has shipped.