php-guzzleHow to stream with PHP Guzzle?
Streaming with PHP Guzzle is a great way to make HTTP requests and receive responses in a continuous stream. To stream with Guzzle, you need to use the stream option when making a request.
$client = new GuzzleHttp\Client();
$response = $client->request('GET', 'http://example.com', [
'stream' => true
]);
The response will be a GuzzleHttp\Psr7\Stream object, which can be used to read the response body in chunks.
$body = $response->getBody();
while (!$body->eof()) {
echo $body->read(1024);
}
The code above will read the response body in chunks of 1024 bytes and echo them out.
The parts of the code are:
$client = new GuzzleHttp\Client();: This creates a new Guzzle client.$response = $client->request('GET', 'http://example.com', ['stream' => true]);: This makes a GET request to the given URL with thestreamoption set totrue.$body = $response->getBody();: This gets the response body as aGuzzleHttp\Psr7\Streamobject.while (!$body->eof()) {: This starts a loop that will run until the end of the stream is reached.echo $body->read(1024);: This reads 1024 bytes from the stream and echoes them out.
Helpful links
More of Php Guzzle
- How to add query parameters to a request with PHP Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
- How to keep alive with Guzzle in PHP?
- How to add a bearer token in PHP Guzzle?
- How to send multiple requests with Guzzle in PHP?
- How to log requests with Guzzle in PHP?
- How to install PHP Guzzle without Composer?
- What version of PHP is required for Guzzle?
- How to update PHP Guzzle?
See more codes...