Retrieve the whole XML response body with Guzzle 6 HTTP Client
The GuzzleHttp\Psr7\Stream implemtents the contract of Psr\Http\Message\StreamInterface which has the following to offer to you:
/** @var $body GuzzleHttp\Psr7\Stream */$contents = (string) $body;
Casting the object to string will call the underlying __toString()
method which is part of the interface. The method name __toString()
is special in PHP.
As the implementation within GuzzleHttp "missed" to provide access to the actual stream handle, so you can't make use of PHP's stream functions which allows more "stream-lined" (stream-like) operations under circumstances, like stream_copy_to_stream
, stream_get_contents
or file_put_contents
. This might not be obvious on first sight.
$client = new \GuzzleHttp\Client();$response = $client->request('GET', $request_url, [ 'headers' => ['Accept' => 'application/xml'], 'timeout' => 120])->getBody()->getContents();$responseXml = simplexml_load_string($response);if ($responseXml instanceof \SimpleXMLElement){ $key_value = (string)$responseXml->key_name;}
I made it this way:
public function execute ($url, $method, $headers) { $client = new GuzzleHttpConnection(); $response = $client->execute($url, $method, $headers); return $this->parseResponse($response);}protected function parseResponse ($response) { return new SimpleXMLElement($response->getBody()->getContents());}
My application returns content in string with XML prepared content, and Guzzle request sends headers with accept param application/xml.