Skip to content

How to return JSON response in Zend framework 2

Last updated on December 21, 2022

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 it for all AJAX integrations.

Let’s see the below example for a better understanding.

namespace <YOUR_MODULE-->\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.

namespace <YOUR_MODULE-->\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.

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments