Search code examples
phplaravellumenguzzle

Assign getBody() to a Variable Guzzle


I am using Guzzle to make Http request, I got a response as I expect but, I want to make some decision base on the response I received but I didn't get I will appreciate any help.

What I have tried so far I try to assign response to a variable

  $result= $response->getBody(); // {"id": 1420053, "name": "guzzle", ...}
  echo $result; //{"id": 1420053, "name": "guzzle", ...}
  $someArray = json_decode($result);
  echo $someArray;  //<!-- Object of class stdClass could not be converted to string (500 Internal Server Error) -->

echo '<pre>' . print_r($response->getBody()->getContents(), true) . '</pre>'; //<pre></pre>

echo '<pre>' . print_r($response->getBody()) . '</pre>'; /***
GuzzleHttp\Psr7\Stream Object
(
    [stream:GuzzleHttp\Psr7\Stream:private
] => Resource id #495
    [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
        (
        )

)
<pre>1</pre>
**/


return response()->json(["body"=>$result],201); //{"body": {},}

I will really appreciate any help

$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');

echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}```

Solution

  • The response is a stream, cast it:

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