Skip to content
Advertisement

Guzzle getContents()->getBody() – Second calls return empty string

I’m calling an API via Guzzle.

public function request(string $method, string $uri, array $data = [], array $headers = [])
{
    $response = $this->getClient()->$method($uri, [
        'headers' => $headers,
        'query' => $data,
    ]);
    echo "1";
    var_dump($response->getBody()->getContents());

    $this->checkError($response);

    echo "2";
    var_dump($response->getBody()->getContents());
    return $response;
}

public function checkError($response)
{
    $json = json_decode($response->getBody()->getContents());
    echo "3";
    var_dump($json);
}

My json test (outputted from “1”) is

{
  "args":{
  },
  "headers":{
    "Authorization":"Basic dXNlcm5hbWU6cGFzc3dvcmQ=",
    "Host":"httpbin.org",
    "User-Agent":"GuzzleHttp/6.3.3 curl/7.59.0 PHP/7.2.4"
  },
  "origin":"1.2.3.4, 1.2.3.4",
  "url":"https://httpbin.org/get"
}

But, in code “2” I have an empty string and in code “3” (output from “checkError” method) I have null.

If I comment out the checkError method, I would expect another time same json in fragment 2, but I have an empty string. Why this behaviour?

Advertisement

Answer

It’s expected behaviour, because response body is a stream (read more in PSR-7 spec).

To be able to read the body again, you need to call ->getBody()->rewind() to rewind the stream to the beginning. Just be aware that it can cause an exception in rare cases, because not all stream types support rewind operation.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement