【问题标题】:Retrieve the whole XML response body with Guzzle 6 HTTP Client使用 Guzzle 6 HTTP 客户端检索整个 XML 响应正文
【发布时间】:2015-10-25 08:58:47
【问题描述】:

我想使用 Guzzle 6 从远程 API 检索 xml 响应。这是我的代码:

$client = new Client([
    'base_uri' => '<my-data-endpoint>',
]);
$response = $client->get('<URI>', [
    'query' => [
        'token' => '<my-token>',
    ],
    'headers' => [
        'Accept' => 'application/xml'
    ]
]);
$body = $response->getBody();

转储$body 将返回GuzzleHttp\Psr7\Stream 对象:

object(GuzzleHttp\Psr7\Stream)[453] 
private 'stream' => resource(6, stream)
...
...

然后我可以调用 $body-&gt;read(1024) 从响应中读取 1024 个字节(将以 xml 读取)。

但是,我想从我的请求中检索整个 XML 响应,因为稍后我需要使用 SimpleXML 扩展来解析它。

我怎样才能最好地从 GuzzleHttp\Psr7\Stream 对象中检索 XML 响应,以便它可用于解析?

while 会循环吗?

while($body->read(1024)) {
    ...
}

非常感谢您的建议。

【问题讨论】:

    标签: php xml http guzzle


    【解决方案1】:

    GuzzleHttp\Psr7\Stream 执行Psr\Http\Message\StreamInterface 的合同,为您提供以下内容:

    /** @var $body GuzzleHttp\Psr7\Stream */
    $contents = (string) $body;
    

    将对象转换为字符串将调用底层的__toString() 方法,该方法是接口的一部分。 method name __toString() is special in PHP

    由于 GuzzleHttp 中的实现“错过”提供对实际流句柄的访问,所以你不能使用 PHP 的流函数,它允许更多“流线型”(stream_copy_to_streamstream_get_contentsfile_put_contents 等情况下的类流)操作。乍一看这可能并不明显。

    【讨论】:

    • 谢谢先生!没有考虑将整个响应体转换为字符串。
    • 我也面临同样的问题。您能否详细说明您的答案,并逐步修复?现在完整的代码会是什么样子?
    【解决方案2】:

    我是这样弄的:

    public function execute ($url, $method, $headers) {
        $client = new GuzzleHttpConnection();
        $response = $client->execute($url, $method, $headers);
    
        return $this->parseResponse($response);
    }
    
    protected function parseResponse ($response) {
        return new SimpleXMLElement($response->getBody()->getContents());
    }
    

    我的应用程序返回带有 XML 准备内容的字符串内容,Guzzle 请求发送带有接受参数 application/xml 的标头。

    【讨论】:

    • 我在使用 laravel 时遇到错误,找不到类 SimpleXMLElement。你有一个简单的解决方法吗?
    • 如果在 PHP 中启用或禁用 SimpleXML 扩展,请使用 phpinfo() 获取信息。如果你使用 PHP 5.1.2 之后的版本,SimpleXML 扩展应该默认启用。
    • 是的,它已启用,我的版本是 5.5.11。我还能做其他检查吗?
    • 能否请您给我们提供一些发生错误的代码?
    • 我应该问一个新问题吗?
    【解决方案3】:
    $client = new \GuzzleHttp\Client();
    $response = $client->request('GET', $request_url, [
        'headers' => ['Accept' => 'application/xml'],
        'timeout' => 120
    ])->getBody()->getContents();
    
    $responseXml = simplexml_load_string($response);
    if ($responseXml instanceof \SimpleXMLElement)
    {
        $key_value = (string)$responseXml->key_name;
    }
    

    【讨论】:

      【解决方案4】:
      $client = new \GuzzleHttp\Client();
      $response = $client->request('GET', 'your URL');
      $response = $response->getBody()->getContents();
      return $response;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2020-06-04
        • 2017-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-08
        相关资源
        最近更新 更多