Home > Backend Development > PHP Tutorial > Guzzle 6: How Do I Get the Response Body as a String?

Guzzle 6: How Do I Get the Response Body as a String?

Susan Sarandon
Release: 2024-11-28 08:32:12
Original
546 people have browsed it

Guzzle 6:  How Do I Get the Response Body as a String?

Guzzlehttp: How to Retrieve Body from Response (Guzzle 6)

In Guzzle 6, the response body is stored in a PSR-7 compliant stream, which is a temporary PHP stream. To retrieve the response body as a string, use one of the following methods:

1. Casting Operator:

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

2. getContents() Method:

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

Difference between the two methods:

  • getContents() returns the remaining contents of the stream, while (string) reads all contents from the beginning.
  • Using getContents() repeatedly will return an empty string unless the stream is rewound.

Example Response Output:

{
    "data" : {
        "token" "fasdfasf-asfasdfasdf-sfasfasf"
    }
}
Copy after login

Additional Notes:

  • The response object also provides methods for accessing headers, status code, and reason phrase.
  • For more information, refer to the Guzzle documentation on PSR-7 responses: http://docs.guzzlephp.org/en/latest/psr7.html#responses

The above is the detailed content of Guzzle 6: How Do I Get the Response Body as a String?. 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