Body
Both request and response messages can contain a body.
You can check to see if a request or response has a body using the getBody()
method:
$response = GuzzleHttp\get('http://httpbin.org/get');
if ($response->getBody()) {
echo $response->getBody();
// JSON string: { ... }
}
The body used in request and response objects is a GuzzleHttp\Stream\StreamInterface
. This stream is used for both uploading data and downloading data. Guzzle will, by default, store the body of a message in a stream that uses PHP temp streams. When the size of the body exceeds 2 MB, the stream will automatically switch to storing data on disk rather than in memory (protecting your application from memory exhaustion).
You can change the body used in a request or response using the setBody()
method:
use GuzzleHttp\Stream\Stream;
$request = $client->createRequest('PUT', 'http://httpbin.org/put');
$request->setBody(Stream::factory('foo'));
The easiest way to create a body for a request is using the static GuzzleHttp\Stream\Stream::factory()
method. This method accepts various inputs like strings, resources returned from fopen()
, and other GuzzleHttp\Stream\StreamInterface
objects.
The body of a request or response can be cast to a string or you can read and write bytes off of the stream as needed.
use GuzzleHttp\Stream\Stream;
$request = $client->createRequest('PUT', 'http://httpbin.org/put', ['body' => 'testing...']);
echo $request->getBody()->read(4);
// test
echo $request->getBody()->read(4);
// ing.
echo $request->getBody()->read(1024);
// ..
var_export($request->eof());
// true
You can find out more about Guzzle stream objects in Streams.