我想使用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->read(1024)
从响应中读取1024字节(这将用xml读取)。
但是,我想从我的请求中检索整个XML响应,因为我以后需要使用SimpleXML
扩展来解析它。
如何从GuzzleHttp\Psr7\Stream
对象中最佳地检索XML,使其可用于解析?
while
循环会走哪条路?
while($body->read(1024)) {
...
}
我很感激你的建议。
发布于 2015-08-03 16:07:22
GuzzleHttp\Psr7\Stream执行http://www.php-fig.org/psr/psr-7/#3-4-psr-http-message-streaminterface的合同,该合同有以下内容提供给您:
/** @var $body GuzzleHttp\Psr7\Stream */
$contents = (string) $body;
将对象转换为string将调用底层__toString()
方法,该方法是接口的一部分。 is special in PHP。
由于GuzzleHttp中的实现“错过”来提供对实际流句柄的访问,所以您不能使用stream_copy_to_stream
的流函数,在类似于stream_copy_to_stream
、stream_get_contents
或file_put_contents
的情况下允许更多的“流衬”(流样)操作。乍一看,这可能并不明显。
发布于 2016-09-03 05:56:37
$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;
}
发布于 2016-02-25 15:58:16
我是这样做的:
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.发送标头。
https://stackoverflow.com/questions/31784141
复制相似问题