如何在 Guzzle 上获得 XML 响应

时间:2021-07-26 08:10:16

标签: php xml https guzzle

我一直在尝试将正文返回的文本解析为 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;

This is how it should look like:

This is how it looks

1 个答案:

答案 0 :(得分:1)

您现在正在执行的回显将触发您使用 __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();