Home >Backend Development >PHP Tutorial >How to Efficiently Get Body Contents from a Guzzle 6 PSR-7 Response?

How to Efficiently Get Body Contents from a Guzzle 6 PSR-7 Response?

DDD
DDDOriginal
2024-11-30 20:34:17770browse

How to Efficiently Get Body Contents from a Guzzle 6 PSR-7 Response?

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:

  • https://docs.guzzlephp.org/en/latest/psr7.html#responses

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!

Statement:
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