2
votes

I want to check the xml based responses from server, here is an example of the response format.

<response>
    <code>success</code>
</response>

My existing code,

use GuzzleHttp\Client;

$client = new Client();
$response = $client->post('http://example.com/verify', [
    'form_params' => [
        'transID' => 1234,
        'orderID' => 6789,
        'token' => '0X45FJH79GD3332'
    ]
]);

$xml = $response->xml();

dd($xml);

However, when I make request to the server error occurs like below.

Call to undefined method GuzzleHttp\Psr7\Response::xml()

1

1 Answers

3
votes

I believe the documentation is outdated (for version 5.3 actually, I suppose you're using 6.*)

They say Sending a request will return a Guzzle\Http\Message\Response object. In this version of Guzzle, you're getting GuzzleHttp\Psr7\Response instead which does not implement xml() method.

You can go and check old version at https://github.com/guzzle/guzzle/blob/5.3/src/Message/Response.php and use that method. Eg. create this:

public function xml(Request $request, array $config = [])
{
    $disableEntities = libxml_disable_entity_loader(true);
    $internalErrors = libxml_use_internal_errors(true);
    try {
        // Allow XML to be retrieved even if there is no response body
        $xml = new \SimpleXMLElement(
            (string) $request->getBody() ?: '<root />',
            isset($config['libxml_options']) ? $config['libxml_options'] : LIBXML_NONET,
            false,
            isset($config['ns']) ? $config['ns'] : '',
            isset($config['ns_is_prefix']) ? $config['ns_is_prefix'] : false
        );
        libxml_disable_entity_loader($disableEntities);
        libxml_use_internal_errors($internalErrors);
    } catch (\Exception $e) {
        libxml_disable_entity_loader($disableEntities);
        libxml_use_internal_errors($internalErrors);
        throw new YourXmlParseException(
            'Unable to parse response body into XML: ' . $e->getMessage(),
            $request,
            $e,
            (libxml_get_last_error()) ?: null
        );
    }
    return $xml;
}