Getting Body Contents from a PSR-7 Response in Guzzle 6
In Guzzle 6, responses adhere to the PSR-7 standard, which utilizes Streams for storing response bodies. To retrieve the body contents, one must retrieve the Stream and subsequently obtain its contents.
Methods for Retrieving Body Contents:
Casting to String:
$contents = (string) $response->getBody();
getContents():
$contents = $response->getBody()->getContents();
Difference between getContents() and Casting:
getContents() returns the remaining stream contents. Subsequent calls to getContents() will return an empty string unless the stream position is reset. Casting, on the other hand, reads all stream data from the beginning to the end.
Example:
$stream = $response->getBody(); $contents = $stream->getContents(); // contents are retrieved $contents = $stream->getContents(); // returns empty string $stream->rewind(); // seek the stream back to the beginning $contents = $stream->getContents(); // contents are retrieved again
Casting to a string performs a single reading operation and returns all data from the stream.
$contents = (string) $response->getBody(); // contents are retrieved $contents = (string) $response->getBody(); // contents are retrieved again
Documentation:
The above is the detailed content of How to Efficiently Get Body Contents from a Guzzle 6 PSR-7 Response?. For more information, please follow other related articles on the PHP Chinese website!