Retrieve Body from a Response in Guzzle 6
When working with Guzzle, the body of a response is stored in a stream. To retrieve it, there are two common approaches.
Using PHP Casting Operator
<br>$contents = (string) $response->getBody();<br>
This operation will read all the data from the beginning of the stream to the end. Subsequent calls to getBody()->getContents() will return an empty string.
Using getBody()->getContents()
$contents = $response->getBody()->getContents();
With getContents(), it only returns the remaining contents of the stream. If you call it twice without seeking the position using rewind() or seek(), it will return an empty string.
Example
Using (string):
$contents = (string) $response->getBody(); echo $contents; // Prints entire response body $contents = (string) $response->getBody(); echo $contents; // Empty string, as data has already been consumed
Using getContents():
$stream = $response->getBody(); $contents = $stream->getContents(); // Prints entire response body $contents = $stream->getContents(); // Empty string, as data has not been reset $stream->rewind(); // Reset stream $contents = $stream->getContents(); // Prints entire response body
Conclusion
Both approaches retrieve the response body. Choose the method based on your specific needs, such as whether you need to read the data only once or multiple times.
The above is the detailed content of How to Efficiently Retrieve the Response Body in Guzzle 6?. For more information, please follow other related articles on the PHP Chinese website!