I wanted to use Guzzle 6 to retrieve an xml response from a remote API. This is my code:
$client = new Client([
'base_uri' => '<my-data-endpoint>',
]);
$response = $client->get('<URI>', [
'query' => [
'token' => '<my-token>',
],
'headers' => [
'Accept' => 'application/xml'
]
]);
$body = $response->getBody();
Vardumping the $body
would return a GuzzleHttp\Psr7\Stream
object:
object(GuzzleHttp\Psr7\Stream)[453]
private 'stream' => resource(6, stream)
...
...
I could then call $body->read(1024)
to read 1024 bytes from the response (which would read in xml).
However, I'd like to retrieve the whole XML response from my request since I will need to parse it later using the SimpleXML
extension.
How can I best retrieve the XML response from GuzzleHttp\Psr7\Stream
object so that it is usable for parsing?
Would the while
loop the way to go?
while($body->read(1024)) {
...
}
I'd appreciate your advice.
As described earlier, you can get the body of a response using the getBody() method. 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.
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc...
Sending Requests You can create a request and then send the request with the client when you're ready: use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);
Debugging when using Guzzle, is quiet easy by providing the debug key in the payload: $client->request('GET', '/url, ['debug' => true]); This is quiet easy and not an issue if your are not passing any body content, using only query string to dump what's been request.
$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;
}
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'your URL');
$response = $response->getBody()->getContents();
return $response;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With