使用Guzzle 6 HTTP Client检索整个XML响应主体 [英] Retrieve the whole XML response body with Guzzle 6 HTTP Client
问题描述
我想使用Guzzle 6从远程API检索xml响应。这是我的代码:
I wanted to use Guzzle 6 to retrieve an xml response from a remote API. This is my code:
$client = new Client([
'base_uri' => '<my-data-endpoint>',
]);
$response = $client->get('<URI>', [
'query' => [
'token' => '<my-token>',
],
'headers' => [
'Accept' => 'application/xml'
]
]);
$body = $response->getBody();
Vardumping $ body
将返回 GuzzleHttp \Psr7 \Stream
对象:
Vardumping the $body
would return a GuzzleHttp\Psr7\Stream
object:
object(GuzzleHttp\Psr7\Stream)[453]
private 'stream' => resource(6, stream)
...
...
I然后可以调用 $ body-> read(1024)
从响应中读取1024个字节(以xml读取)。
I could then call $body->read(1024)
to read 1024 bytes from the response (which would read in xml).
但是,我想从我的请求中检索整个XML响应,因为我需要稍后使用 SimpleXML
扩展来解析它。
However, I'd like to retrieve the whole XML response from my request since I will need to parse it later using the SimpleXML
extension.
如何从 GuzzleHttp \Psr7 \Stream
对象中最佳地检索XML响应,以便它可用于解析?
How can I best retrieve the XML response from GuzzleHttp\Psr7\Stream
object so that it is usable for parsing?
而
是否会循环播放?
while($body->read(1024)) {
...
}
我很感激你的建议。
推荐答案
GuzzleHttp \\Psr7 \Stream 实现 Psr \Http\Message\StreamInterface ,其中包含以下内容:
The GuzzleHttp\Psr7\Stream implemtents the contract of Psr\Http\Message\StreamInterface which has the following to offer to you:
/** @var $body GuzzleHttp\Psr7\Stream */
$contents = (string) $body;
将对象转换为字符串将调用底层的 __ toString()
方法是接口的一部分。 方法名 __ toString()
在PHP中很特别。
Casting the object to string will call the underlying __toString()
method which is part of the interface. The method name __toString()
is special in PHP.
由于 GuzzleHttp 中的实现错过提供对实际流句柄的访问,所以你无法制作使用PHP的流功能,允许在环境下进行更多流式(流式)操作,例如 stream_copy_to_stream
, stream_get_contents
或 file_put_contents
。这可能在第一眼看上去并不明显。
As the implementation within GuzzleHttp "missed" to provide access to the actual stream handle, so you can't make use of PHP's stream functions which allows more "stream-lined" (stream-like) operations under circumstances, like stream_copy_to_stream
, stream_get_contents
or file_put_contents
. This might not be obvious on first sight.
这篇关于使用Guzzle 6 HTTP Client检索整个XML响应主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!