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:

  1. $response = GuzzleHttp\get('http://httpbin.org/get');
  2. if ($response->getBody()) {
  3. echo $response->getBody();
  4. // JSON string: { ... }
  5. }

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:

  1. use GuzzleHttp\Stream\Stream;
  2. $request = $client->createRequest('PUT', 'http://httpbin.org/put');
  3. $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.

  1. use GuzzleHttp\Stream\Stream;
  2. $request = $client->createRequest('PUT', 'http://httpbin.org/put', ['body' => 'testing...']);
  3. echo $request->getBody()->read(4);
  4. // test
  5. echo $request->getBody()->read(4);
  6. // ing.
  7. echo $request->getBody()->read(1024);
  8. // ..
  9. var_export($request->eof());
  10. // true

You can find out more about Guzzle stream objects in Streams.