guzzle 6.0 call to undefined method GuzzleHttp\Psr7\Response::xml()

三世轮回 提交于 2019-12-11 03:38:07

问题


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:


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 as an example for your code:

public function xml(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) $this->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 XmlParseException(
                'Unable to parse response body into XML: ' . $e->getMessage(),
                $this,
                $e,
                (libxml_get_last_error()) ?: null
            );
        }
        return $xml;
    }


来源:https://stackoverflow.com/questions/32232395/guzzle-6-0-call-to-undefined-method-guzzlehttp-psr7-responsexml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!