1

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?

Eleandro Duzentos
  • 1,370
  • 18
  • 36
  • Why you don't using `Zend\Http\Response`? – Mirek Kowieski Jul 28 '17 at 23:07
  • 'Cause i'm not using **Zend Framework** at all, it's just **Zend Diactoros**, the Zend Framework PSR-7 implementation. – Eleandro Duzentos Jul 28 '17 at 23:09
  • Ok. Your second solution is correct, but when you putting some strings to response body then it works like `echo`, so you don't need your `echo` on the end of file. – Mirek Kowieski Jul 28 '17 at 23:14
  • 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. – Eleandro Duzentos Jul 28 '17 at 23:21

1 Answers1

0

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();
Eleandro Duzentos
  • 1,370
  • 18
  • 36
  • 1
    `$response = new Response();` `$response->getBody()->write("This is a response");` `echo $response->getBody();` It is the same. – Mirek Kowieski Jul 28 '17 at 23:25