如何在guzzle上获得xml响应

pu82cl6c  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(422)

我一直在尝试将主体返回的文本解析为xml(应该以xml形式返回),但到目前为止,它只是像文本一样返回。下面是代码和应该显示的内容。

require 'vendor/autoload.php';
    use GuzzleHttp\Client;
    use GuzzleHttp\Psr7\Response;
    use GuzzleHttp\Exception\RequestException;
    use GuzzleHttp\Promise\Promise;
    use GuzzleHttp\Psr7\Request;
    $client = new GuzzleHttp\Client();
    $options = [
        'headers' => ['Accept'=>'application/xml'],
        'auth' => ['Deversor-Channel', '?1_sIWVZ((ujV)kDBM!6O5!AFAQM*K*yr(?E.(g='],
        'body' => "<request>
                        <hotel_id>345786
                        </hotel_id>
                        <last_change>2021-07-19</last_change>
                    </request>",
    ];
    $res = $client->request('POST', 'https://secure-supply-xml.booking.com/hotels/xml/reservations', $options);
    echo $res->getStatusCode();
    // "200"
    echo $res->getBody();
    // {"type":"User"...'
    $xml = simplexml_load_string($res->getBody(),'SimpleXMLElement',LIBXML_NOCDATA);
    echo $xml;

它应该是这样的:
这就是它的样子

66bbxpm5

66bbxpm51#

你现在做的回音会触发 __toString() 使用创建的simplexmlelement的方法 simplexml_load_string() ,它本质上是该对象的字符串内容。
你要找的是 $xml->asXML() ,它将输出格式正确的xml字符串。您可能还需要添加一个 Content-Type 用于某些浏览器拾取xml内容的标题。请尝试以下操作:

require 'vendor/autoload.php';
    use GuzzleHttp\Client;
    use GuzzleHttp\Psr7\Response;
    use GuzzleHttp\Exception\RequestException;
    use GuzzleHttp\Promise\Promise;
    use GuzzleHttp\Psr7\Request;
    $client = new GuzzleHttp\Client();
    $options = [
        'headers' => ['Accept'=>'application/xml'],
        'auth' => ['Deversor-Channel', '?1_sIWVZ((ujV)kDBM!6O5!AFAQM*K*yr(?E.(g='],
        'body' => "<request>
                        <hotel_id>345786
                        </hotel_id>
                        <last_change>2021-07-19</last_change>
                    </request>",
    ];
    $res = $client->request('POST', 'https://secure-supply-xml.booking.com/hotels/xml/reservations', $options);
    echo $res->getStatusCode();
    // "200"
    echo $res->getBody();
    // {"type":"User"...'
    $xml = simplexml_load_string($res->getBody(),'SimpleXMLElement',LIBXML_NOCDATA);

    header('Content-Type: application/xml');
    echo $xml->asXML();

相关问题