$response->getBody()->getContents() returning empty string

3.5k Views Asked by At

I have the code below:

<?php

use Zend\Diactoros\Response;

$response = new Response('This is the response content');

echo $response->getBody()->getContents();
echo $response->getBody();

I'm passing the body directly in the constructor.

I'm trying to get the body of this response, nothing more then it, but when i call the getBody() or the getBody()->getContents() it's give me a empty string.

I've tried another alternative that works:

<?php

use Zend\Diactoros\Response;

$response = new Response;

$response->getBody()->write('This is the response content');

echo $response->getBody()->getContents();
echo $response->getBody();

and it outputs:

This is the response content This is the response content

Why the first and short form isn't working?

1

There are 1 best solutions below

1
On BEST ANSWER

I found the problem, that's was my fault.

Actually, the Response __constructor gets a StreamInterface as first parameter, not a string.

The StreamInterface implementation is where you have to write your body, other wise, you get no response.

Here is the good approach:

$stream = new Stream('php://temp', 'rw');

$stream->write('This is a response');

$response = (new Response($stream));

echo $response->getBody();