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

How to Retrieve the Response Body in Guzzle 6?

Susan Sarandon
Release: 2024-11-30 17:06:12
Original
523 people have browsed it

How to Retrieve the Response Body in Guzzle 6?

Retrieving the Body of a Response in Guzzle 6

Guzzle 6, a popular HTTP client library for PHP, utilizes the PSR-7 standard which mandates the use of streams to store the body of a message. To retrieve this body as a string, utilize one of the following methods:

String Casting Operator

$contents = (string) $response->getBody();
Copy after login

Using getContents()

$contents = $response->getBody()->getContents();
Copy after login

Key Difference:

  • getContents() returns the remaining contents of the stream, meaning a subsequent call will return an empty string unless the stream position is reset using rewind or seek.
  • Casting to a string will read all data from the stream, regardless of previous operations.

For example:

$stream = $response->getBody();
$contents = $stream->getContents(); // returns all contents
$contents = $stream->getContents(); // empty string
$stream->rewind();  // reset stream position
$contents = $stream->getContents();  // returns all contents again
Copy after login

In contrast:

$contents = (string) $response->getBody(); // returns all contents
$contents = (string) $response->getBody(); // returns all contents again
Copy after login

For more details, refer to the Guzzle documentation: http://docs.guzzlephp.org/en/latest/psr7.html#responses

The above is the detailed content of How to 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