How to return JSON response in Zend framework 2

In this post, I just want to show you how to return the response in JSON format in the correct way in ZF2.Returning JSON response is very useful and we almost use for all AJAX integrations.

Let’s see the below example for better understanding.

\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Json\Json;

class ContactController extends AbstractActionController {

     public function getListAction() {
            $contacts = array( 'foo' => 'bar' );
            $response = $this->getResponse();
            $response->getHeaders()->addHeaderLine( 'Content-Type', 'application/json' );
            $response->setContent(json_encode($contacts));
            return $response;
     }

}

Actually above solution is pretty much the clearest solution and correct way, but actually, you can output the JSON string or PHP variables and simply exit() as it’s shown in the below example.

\Controller;

use Zend\Mvc\Controller\AbstractActionController;

class ContactController extends AbstractActionController {

     public function getListAction() {
            $contacts = array( 'foo' => 'bar' );
            echo json_encode($contacts);
            exit; // echo and exit - don't rendered HTML
     }

}

That’s it.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

DMCA.com Protection Status