[英]Retrieve the whole XML response body with Guzzle 6 HTTP Client
我想使用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();
Vardumping $body
将返回GuzzleHttp\\Psr7\\Stream
对象:
object(GuzzleHttp\Psr7\Stream)[453]
private 'stream' => resource(6, stream)
...
...
然后我可以调用$body->read(1024)
从响应中读取1024个字节(将以xml读取)。
但是,我想从我的请求中检索整个XML响应,因为我稍后需要使用SimpleXML
扩展来解析它。
如何从GuzzleHttp\\Psr7\\Stream
对象中最好地检索XML响应,以便它可用于解析?
while
循环是否可行?
while($body->read(1024)) {
...
}
我很感激你的意见。
GuzzleHttp \\ Psr7 \\ Stream实现Psr \\ Http \\ Message \\ StreamInterface的合同,其中包含以下内容:
/** @var $body GuzzleHttp\Psr7\Stream */
$contents = (string) $body;
将对象转换为字符串将调用底层的__toString()
方法,该方法是接口的一部分。 方法名称__toString()
在PHP中是特殊的 。
由于GuzzleHttp中的实现“错过”提供对实际流句柄的访问,因此您无法利用PHP的流函数,这些函数允许在诸如stream_copy_to_stream
, stream_get_contents
类的情况下进行更多“流式”( 流式 )操作。 file_put_contents
。 这可能在第一眼看上去并不明显。
我是这样做的:
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请求使用accept param application / xml发送标头。
$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;
}
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'your URL');
$response = $response->getBody()->getContents();
return $response;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.