php-guzzleHow to get the response body in JSON format in PHP Guzzle?
To get the response body in JSON format in PHP Guzzle, you can use the json()
method. This method will return the response body as a JSON object.
Example code
$client = new GuzzleHttp\Client();
$response = $client->request('GET', 'http://example.com/api/v1/users');
$data = $response->json();
Output example
[
{
"id": 1,
"name": "John Doe"
},
{
"id": 2,
"name": "Jane Doe"
}
]
Code explanation
$client = new GuzzleHttp\Client();
: creates a new Guzzle client.$response = $client->request('GET', 'http://example.com/api/v1/users');
: sends a GET request to the specified URL and stores the response in the$response
variable.$data = $response->json();
: parses the response body as a JSON object and stores it in the$data
variable.
Helpful links
More of Php Guzzle
- How to set a user agent in PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to add an SSL certificate to a request with PHP Guzzle?
- How to handle a RequestException with PHP Guzzle?
- How to make an asynchronous send with PHP Guzzle?
- How to convert a response to an array with PHP Guzzle?
- What version of PHP is required for Guzzle?
- How to make HTTP request with PHP Guzzle?
- How to stream with PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
See more codes...