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
Release: 2024-11-30 20:34:17
Original
708 people have browsed it

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

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template