Responses
Responses are the HTTP messages a client receives from a server after sending an HTTP request message.
Start-Line
The start-line of a response contains the protocol and protocol version, status code, and reason phrase.
$response = GuzzleHttp\get('http://httpbin.org/get');
echo $response->getStatusCode();
// 200
echo $response->getReasonPhrase();
// OK
echo $response->getProtocolVersion();
// 1.1
Body
As described earlier, you can get the body of a response using the getBody()
method.
if ($body = $response->getBody()) {
echo $body;
// Cast to a string: { ... }
$body->seek(0);
// Rewind the body
$body->read(1024);
// Read bytes of the body
}
When working with JSON responses, you can use the json()
method of a response:
$json = $response->json();
Note
Guzzle uses the json_decode()
method of PHP and uses arrays rather than stdClass
objects for objects.
You can use the xml()
method when working with XML data.
$xml = $response->xml();
Note
Guzzle uses the SimpleXMLElement
objects when converting response bodies to XML.
Effective URL
The URL that was ultimately accessed that returned a response can be accessed using the getEffectiveUrl()
method of a response. This method will return the URL of a request or the URL of the last redirected URL if any redirects occurred while transferring a request.
$response = GuzzleHttp\get('http://httpbin.org/get');
echo $response->getEffectiveUrl();
// http://httpbin.org/get
$response = GuzzleHttp\get('http://httpbin.org/redirect-to?url=http://www.google.com');
echo $response->getEffectiveUrl();
// http://www.google.com