Php 使用Guzzle 6 HTTP客户端检索整个XML响应主体
我想使用Guzzle 6从远程API检索xml响应。这是我的代码:Php 使用Guzzle 6 HTTP客户端检索整个XML响应主体,php,xml,http,guzzle,Php,Xml,Http,Guzzle,我想使用Guzzle 6从远程API检索xml响应。这是我的代码: $client = new Client([ 'base_uri' => '<my-data-endpoint>', ]); $response = $client->get('<URI>', [ 'query' => [ 'token' => '<my-token>', ], 'headers' => [
$client = new Client([
'base_uri' => '<my-data-endpoint>',
]);
$response = $client->get('<URI>', [
'query' => [
'token' => '<my-token>',
],
'headers' => [
'Accept' => 'application/xml'
]
]);
$body = $response->getBody();
然后,我可以调用$body->read(1024)
从响应中读取1024个字节(以xml格式读取)
但是,我希望从请求中检索整个XML响应,因为稍后需要使用SimpleXML
扩展对其进行解析
如何最好地从GuzzleHttp\Psr7\Stream
对象检索XML响应,使其可用于解析
while
会循环前进吗
while($body->read(1024)) {
...
}
非常感谢您的建议。合同执行人向您提供以下内容:
/** @var $body GuzzleHttp\Psr7\Stream */
$contents = (string) $body;
将对象强制转换为字符串将调用作为接口一部分的底层\uuu toString()
方法。这个
由于GuzzleHttp中的实现“错过”了提供对实际流句柄的访问,因此您不能使用PHP的流函数,它允许在诸如stream\u copy\u to\u stream
、stream\u get\u contents
或file\u put\u 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 paramapplication/XML的标题 谢谢你,先生!我没有考虑将整个响应体都转换为字符串。我面临着同样的问题。你能详细说明一下你的答案吗,并逐步修正?现在完整的代码是什么样子的?我正在使用laravel,发现一个错误,没有找到类
SimpleXMLElement
。是否有简单的修复方法?如果在PHP中启用或禁用了SimpleXML扩展,请使用phpinfo()获取信息。如果您使用的是比5.1.2更新的PHP,默认情况下应启用SimpleXML扩展。是的,它已启用,我的版本为5.5.11。我还可以做其他检查吗?你能给我们提供一些发生错误的代码吗?我应该问一个新问题吗?
$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', $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;