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:
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
You can retrieve headers from the response:
// Check if a header exists.
if ($response->hasHeader('Content-Length')) {
echo "It exists";
}
// Get a header from the response.
echo $response->getHeader('Content-Length')[0];
// Get all of the response headers.
foreach ($response->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "\r\n";
}
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.
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;
// Read 10 bytes from the body
$tenBytes = $body->read(10);
// Read the remaining contents of the body as a string
$remainingBytes = $body->getContents();