JSON response from controller action in CakePHP 2

We know that there is a layout for XML and AJAX response in CakePHP that did their job well. But what can we do to get an easy JSON response from a controller action?

It is easier then i thought, with the new CakeResponse.

Create an array that you want to convert into a JSON string in your controller action and just one line of code generates your response:

return new CakeResponse(array('body' => json_encode($array)));

No $this->set() or echo $string is needed anymore.

I use this to answer requests from an Android App and it works nice and fast. 🙂

7 thoughts on “JSON response from controller action in CakePHP 2

  1. Ernesto Campohermoso

    Thank you!, your post help me so much. Just a comment, in order to set the content type of the response to “application/json” you can do:

    return new CakeResponse(array(‘body’ => json_encode($array)),’type’ => ‘json’);

    Reply
  2. mark

    That what my answer implied: To re-use the existent one.

    $this->request->body(json_encode($array));
    $this->request->type(‘json’);
    $this->autoRender = false;

    Then you also don’t need to return.

    PS: Or just use the nice JsonView as documented.

    Reply

Leave a Reply