如何使用枪口检索XML

问题描述 投票:0回答:1

我想从某个URL中检索响应,但是该URL使用xml返回它的响应。有没有办法使用Guzzle检索此响应?在Guzzle 5.3中,我们可以轻松地执行以下操作:

$ response-> xml()

因此,这将解析xml内容。现在,当我尝试在Guzzle 6.2中使用相同的代码时,它不再起作用。下面是我的代码

$response = $client->get($this->url);
$resp = $response->xml();

但是这不起作用。我也在下面尝试过

$response = $client->get($this->url);
$response = $response->getBody()->getContents();
$responseXml = simplexml_load_string($response);
if ($responseXml instanceof \SimpleXMLElement)
{
   $key_value = (string)$responseXml->key_name;
   return $key_value;
 }

但是这不起作用。关于如何检索xml数据的任何想法吗?

laravel guzzle guzzle6 guzzlehttp
1个回答
0
投票

知道了。原来我只需要添加

'ACCEPT'=>'application / json'

至我请求的标头参数。然后,我可以按照下面的代码所示对xml进行解码

$provider_type = 'application/xml';
$response = $this->client->get($this->url, $param_data);            
$response = $response->getBody()->getContents();

    switch ($provider_type) {
        case 'application/xml':
            $encode_response = json_encode(simplexml_load_string($response));   

            $decode_response = json_decode($encode_response, TRUE);
            return $decode_response;

        default: // Response json
            $encode_response = json_encode($response);   

            $decode_response = json_decode($encode_response, TRUE);
            return json_decode($decode_response, TRUE);                

    }
© www.soinside.com 2019 - 2024. All rights reserved.