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 thestream
option set totrue
.$body = $response->getBody();
: This gets the response body as aGuzzleHttp\Psr7\Stream
object.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 set a user agent in PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to add an SSL certificate to a request with PHP Guzzle?
- How to handle a RequestException with PHP Guzzle?
- How to make an asynchronous send with PHP Guzzle?
- How to convert a response to an array with PHP Guzzle?
- What version of PHP is required for Guzzle?
- How to make HTTP request with PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
See more codes...