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 use PHP Guzzle to make a batch request?
- What version of PHP is required for Guzzle?
- How to set a user agent in PHP Guzzle?
- How to post form data with PHP Guzzle?
- How to add a bearer token in PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to update PHP Guzzle?
- How to handle a RequestException with PHP Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
See more codes...