Skip to content

Streaming Responses and SSE ​

Use fetch_stream() or the handler's stream() method to receive a StreamedResponse. It exposes stream() for chunks, lines() for newline-delimited text, sse() for event parsing, and buffer() to consume the remaining body into a regular response.

php
$stream = fetch_stream('https://api.example.test/v1/log');

foreach ($stream->lines() as $line) {
    // Process each line before reading the next one.
}

The underlying stream is consumed as it is read; it is generally a one-pass resource. SSE support parses events but does not automatically reconnect or implement application retry policy.

Streaming uses a separate direct Guzzle request path. It does not pass through the usual MockServer, middleware, retry, or cache pipeline. Use a Guzzle MockHandler for deterministic streaming tests. Streaming I/O is synchronous.

php
<?php

declare(strict_types=1);

require dirname(__DIR__, 3).'/vendor/autoload.php';

use Fetch\Enum\Method;
use Fetch\Http\ClientHandler;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response as GuzzleResponse;

$mock = new MockHandler([
    new GuzzleResponse(
        200,
        ['Content-Type' => 'text/plain'],
        "first line\nsecond line\n",
    ),
]);
$client = new GuzzleClient(['handler' => HandlerStack::create($mock)]);
$handler = ClientHandler::createWithClient($client);
$stream = $handler->stream(Method::GET, 'https://api.example.test/log');
$lines = iterator_to_array($stream->lines(), false);

if ($lines !== ['first line', 'second line']) {
    throw new RuntimeException(
        'The streamed response example returned unexpected lines.',
    );
}

Released under the MIT License.