使用Guzzle 6 HTTP Client检索整个XML响应主体

luq*_*o33 11 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' => [
        'Accept' => 'application/xml'
    ]
]);
$body = $response->getBody();
Run Code Online (Sandbox Code Playgroud)

Vardumping $body会返回一个GuzzleHttp\Psr7\Stream对象:

object(GuzzleHttp\Psr7\Stream)[453] 
private 'stream' => resource(6, stream)
...
...
Run Code Online (Sandbox Code Playgroud)

然后,我可以调用$body->read(1024)从响应中读取1024个字节(将以xml读取).

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

如何从GuzzleHttp\Psr7\Stream对象中最佳地检索XML响应,以便它可用于解析?

将在while环要走的路?

while($body->read(1024)) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

我很感激你的意见.

hak*_*kre 14

GuzzleHttp\PSR7 \流 implemtents合同PSR\HTTP \信息\ StreamInterface它有以下提供给你:

/** @var $body GuzzleHttp\Psr7\Stream */
$contents = (string) $body;
Run Code Online (Sandbox Code Playgroud)

将对象转换为字符串将调用__toString()作为接口一部分的基础方法.该方法的名称__toString()在PHP是特殊的.

由于GuzzleHttp内部的实现"错过"提供对实际流句柄的访问,因此你无法利用PHP的流函数,这允许更多的"流式"(流式)操作情况下stream_copy_to_stream,stream_get_contents或者file_put_contents.这可能在第一眼看上去并不明显.


sNI*_*sss 5

$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;
}
Run Code Online (Sandbox Code Playgroud)