Using Responses

In the previous examples, we retrieved a $response variable or we were delivered a response from a promise. The response object implements a PSR-7 response, Psr\Http\Message\ResponseInterface, and contains lots of helpful information.

You can get the status code and reason phrase of the response:

1. $code = $response->getStatusCode(); // 200
2. $reason = $response->getReasonPhrase(); // OK

You can retrieve headers from the response:

1. // Check if a header exists.
2. if ($response->hasHeader('Content-Length')) {
3. echo "It exists";
4. }

6. // Get a header from the response.
7. echo $response->getHeader('Content-Length')[0];

9. // Get all of the response headers.
10. foreach ($response->getHeaders() as $name => $values) {
11. echo $name . ': ' . implode(', ', $values) . "\r\n";
12. }

The body of a response can be retrieved using the getBody method. The body can be used as a string, cast to a string, or used as a stream like object.

1. $body = $response->getBody();
2. // Implicitly cast the body to a string and echo it
3. echo $body;
4. // Explicitly cast the body to a string
5. $stringBody = (string) $body;
6. // Read 10 bytes from the body
7. $tenBytes = $body->read(10);
8. // Read the remaining contents of the body as a string
9. $remainingBytes = $body->getContents();