$request = new HttpRequest(
url: 'https://api.example.com/events',
method: 'GET',
headers: [
'Accept' => 'text/event-stream',
'Cache-Control' => 'no-cache',
],
body: [],
options: ['stream' => true]
);
$response = $client->withRequest($request)->get();
$buffer = '';
foreach ($response->stream() as $chunk) {
// Add the chunk to our buffer
$buffer .= $chunk;
// Process complete events (SSE events are separated by double newlines)
while (($pos = strpos($buffer, "\n\n")) !== false) {
// Extract and process the event
$event = substr($buffer, 0, $pos);
$buffer = substr($buffer, $pos + 2);
// Parse the event (SSE format: "field: value")
$parsedEvent = [];
foreach (explode("\n", $event) as $line) {
if (preg_match('/^([^:]+):\s*(.*)$/', $line, $matches)) {
$field = $matches[1];
$value = $matches[2];
$parsedEvent[$field] = $value;
}
}
// Process the parsed event
if (isset($parsedEvent['event'], $parsedEvent['data'])) {
$eventType = $parsedEvent['event'];
$eventData = $parsedEvent['data'];
echo "Received event type: $eventType\n";
echo "Event data: $eventData\n";
// You could also parse the data as JSON if appropriate
if ($eventType === 'update') {
$data = json_decode($eventData, true);
if ($data) {
echo "Processed update: {$data['message']}\n";
}
}
}
}
}
// @doctest id="008d"