Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get response body on php guzzle?

Tags:

php

guzzle

use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('http://httpbin.org/post', array());

How i can get body response?

getBody not returned response body

echo '<pre>' . print_r($response->getBody(), true) . '</pre>';
GuzzleHttp\Psr7\Stream Object
(
    [stream:GuzzleHttp\Psr7\Stream:private] => Resource id #80
    [size:GuzzleHttp\Psr7\Stream:private] => 
    [seekable:GuzzleHttp\Psr7\Stream:private] => 1
    [readable:GuzzleHttp\Psr7\Stream:private] => 1
    [writable:GuzzleHttp\Psr7\Stream:private] => 1
    [uri:GuzzleHttp\Psr7\Stream:private] => php://temp
    [customMetadata:GuzzleHttp\Psr7\Stream:private] => Array
        (
        )

)

how print body response?

like image 877
Alexander Avatar asked Mar 16 '23 00:03

Alexander


1 Answers

You can use the getContents method to pull the body of the response.

$response = $this->client->get("url_path", [
                'headers' => ['Authorization' => 'Bearer ' . $my_token]
            ]);
$response_body = $response->getBody()->getContents();
print_r($response_body);

When you pull make guzzle requests, you'll typically put it in a try catch block. Also, you'll want to then decode that response as JSON so you can use it like an object. Here's an example of how to do it. In this case, I am authenticating with a server:

    try {

        $response = $this->client->post($my_authentication_path, [
            'headers' => ['Authorization' => 'Basic ' . $this->base_64_key,
                            'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
                            ],
            'form_params'    => ['grant_type' => 'password',
                            'username' => 'my_user_name',
                            'password' => 'my_password']
        ]);

        $response_body = $response->getBody()->getContents();

    } catch (GuzzleHttp\Exception\RequestException $e){
        $response_object = $e->getResponse();
        //log or print the error here.
        return false;
    } //end catch

    $authentication_response = json_decode($response_body);
    print_r($authentication_response);
like image 193
Maximus Avatar answered Mar 24 '23 16:03

Maximus