Home > Backend Development > PHP Tutorial > How to Efficiently Retrieve the Response Body in Guzzle 6?

How to Efficiently Retrieve the Response Body in Guzzle 6?

Barbara Streisand
Release: 2024-11-28 13:54:14
Original
643 people have browsed it

How to Efficiently Retrieve the Response Body in Guzzle 6?

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();
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template