phpslimslim-3

Accessing the Data of a Slim 3 Response Object


I'm using a PHP framework called Slim 3 and I would like to inspect my Response object and I wonder why this is not possible.

The official documentation states that a Response` object implements PSR 7 ResponseInterface which allows me to inspect the body.

When I var_dump($response->getBody(); I only see a protected body and I can't find my $stack content anywhere.

The documentation states this and I think this is the reason. Can you confirm this please?

Reminder The Response object is immutable. This method returns a copy of the Response object that contains the new body.

Source: https://www.slimframework.com/docs/objects/response.html

PHP Controller class

class Controller
{
    public function index($request, $response, $args)
    {
        // code

        $stack    = array($cars, $manufacturers);
        $response = $response->withJson($stack);

        return $response->withStatus(200);
    }
}

Output of var_dump

class Slim\Http\Response#201 (5) {
  protected $status =>
  int(200)
  protected $reasonPhrase =>
  string(2) "OK"
  protected $protocolVersion =>
  string(3) "1.1"
  protected $headers =>
  class Slim\Http\Headers#200 (1) {
    protected $data =>
    array(1) {
      'content-type' =>
      array(2) {
        ...
      }
    }
  }
  protected $body =>
  class Slim\Http\Body#202 (7) {
    protected $stream =>
    resource(87) of type (stream)
    protected $meta =>
    array(6) {
      'wrapper_type' =>
      string(3) "PHP"
      'stream_type' =>
      string(4) "TEMP"
      'mode' =>
      string(3) "w+b"
      'unread_bytes' =>
      int(0)
      'seekable' =>
      bool(true)
      'uri' =>
      string(10) "php://temp"
    }
    protected $readable =>
    NULL
    protected $writable =>
    bool(true)
    protected $seekable =>
    NULL
    protected $size =>
    NULL
    protected $isPipe =>
    NULL
  }
}

Solution

  • The content is written to the HTTP response body stream.

    $content = $response->getBody()->__toString();
    

    or

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