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.

  1. $response = GuzzleHttp\get('http://httpbin.org/get');
  2. echo $response->getStatusCode();
  3. // 200
  4. echo $response->getReasonPhrase();
  5. // OK
  6. echo $response->getProtocolVersion();
  7. // 1.1

Body

As described earlier, you can get the body of a response using the getBody() method.

  1. if ($body = $response->getBody()) {
  2. echo $body;
  3. // Cast to a string: { ... }
  4. $body->seek(0);
  5. // Rewind the body
  6. $body->read(1024);
  7. // Read bytes of the body
  8. }

When working with JSON responses, you can use the json() method of a response:

  1. $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.

  1. $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.

  1. $response = GuzzleHttp\get('http://httpbin.org/get');
  2. echo $response->getEffectiveUrl();
  3. // http://httpbin.org/get
  4. $response = GuzzleHttp\get('http://httpbin.org/redirect-to?url=http://www.google.com');
  5. echo $response->getEffectiveUrl();
  6. // http://www.google.com