Body

Both request and response messages can contain a body.

You can retrieve the body of a message using the getBody() method:

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

The body used in request and response objects is a Psr\Http\Message\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).

The easiest way to create a body for a message is using the stream_for function from the GuzzleHttp\Psr7 namespace — GuzzleHttp\Psr7\stream_for. This function accepts strings, resources, callables, iterators, other streamables, and returns an instance of Psr\Http\Message\StreamInterface.

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. $response = $client->request('GET', 'http://httpbin.org/get');
  3. echo $response->getBody()->read(4);
  4. echo $response->getBody()->read(4);
  5. echo $response->getBody()->read(1024);
  6. var_export($response->eof());