Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

php - Retrieve the whole XML response body with Guzzle 6 HTTP Client

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 the $body would return a GuzzleHttpPsr7Stream object:

object(GuzzleHttpPsr7Stream)[453] 
private 'stream' => resource(6, stream)
...
...

I could then call $body->read(1024) to read 1024 bytes from the response (which would read in xml).

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.

How can I best retrieve the XML response from GuzzleHttpPsr7Stream object so that it is usable for parsing?

Would the while loop the way to go?

while($body->read(1024)) {
    ...
}

I'd appreciate your advice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The GuzzleHttpPsr7Stream implemtents the contract of PsrHttpMessageStreamInterface which has the following to offer to you:

/** @var $body GuzzleHttpPsr7Stream */
$contents = (string) $body;

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...