Previously in Guzzle 5.3:
$response = $client->get(\'http://httpbin.org/get\');
$array = $response->json(); // Yoohoo
var_dump($array[0][\'origin\']);
$response
is instance of PSR-7 ResponseInterface
. For more details see https://www.php-fig.org/psr/psr-7/#3-interfaces
getBody()
returns StreamInterface:
/**
* Gets the body of the message.
*
* @return StreamInterface Returns the body as a stream.
*/
public function getBody();
StreamInterface
implements __toString()
which does
Reads all data from the stream into a string, from the beginning to end.
Therefore, to read body as string, you have to cast it to string:
$stringBody = (string) $response->getBody()
json_decode($response->getBody()
is not the best solution as it magically casts stream into string for you. json_decode()
requires string as 1st argument.$response->getBody()->getContents()
unless you know what you're doing. If you read documentation for getContents()
, it says: Returns the remaining contents in a string
. Therefore, calling getContents()
reads the rest of the stream and calling it again returns nothing because stream is already at the end. You'd have to rewind the stream between those calls.