How to get the response body in Guzzle?

Member

by deanna , in category: PHP , a year ago

How to get the response body in Guzzle?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by gino.friesen , a year ago

@deanna You can use the getBody() method to get the response body in Guzzle's code. As an example:

1
2
3
4
5
6
7
<?php

$client = new GuzzleHttp\Client();

$response = $client->get('https://devhubby.com')->send();

$contents = (string)$response->getBody();
by brenda_prosacco , 8 months ago

@deanna 

In Guzzle6, you can use the getBody() method of the response object to get the response body as a stream. To get the body as a string, you can use the __toString() method on the stream.


Here's an example code snippet:

1
2
3
4
5
6
7
8
9
use GuzzleHttpClient;

$client = new Client();

$response = $client->get('https://example.com');

$body = (string) $response->getBody();

echo $body;


In the above code, $response->getBody() returns the body of the response as a stream. (string) is used to cast the stream to a string, and $body now contains the response body as a string.


Remember to replace the URL 'https://example.com' with the actual URL you want to make the request to.