Returning JSON in a Zend Controller’s Action

There are three basic ways that you can achieve that. First of all what’s the task? You’ve an array, either from a database result or whatever, and you encode it JSON with Zend_Json::encode($array)

// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
 
		$this->view->data = Zend_Json::encode($data);	
	}	
}

The result in general is a specially formatted string. So you can simply set it up to a view member variable and pass it to the view.

// index/index.phtml
echo $this->data

In that case you’ve a .phtml file to maintain, so lets just return the string and “setNoRender” the view in our second try.

// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
 
		echo Zend_Json::encode($data);	
 
		$this->_helper->viewRenderer->setNoRender(true);
	}	
}

Actually this is pretty much the most clear solution, but actually you can output the JSON string and simply exit() as it’s shown in our third example.

// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
 
		echo Zend_Json::encode($data);	
 
		exit();
	}	
}

Which one is to be used is up to the developer’s choice, mine is the third one as it’s the minimal one.

5 thoughts on “Returning JSON in a Zend Controller’s Action

  1. Please don’t use the third method (exit), because then existing postDispatch methods or -plugins are not executed!

    The second solution or ContextSwitch/AjaxSwitch is the best choice.

  2. Its not always what or how we prefer doing things, most of the time one should stick to the official methods/ways of doing stuff.

    I think this is the significant different between Zend Framework and other frameworks, ZF enforces good coding practices.

    If you want to “roll your own” in a variety of ways then rather use other frameworks like Codeigniter, Yii etc.

    Although ZF can be extended to suit your needs 100%, a solid convention for doing this also exist – with ZF is hardly ever a case of “where the hell do I find this method” or “Why are these classes but these ones are global functions”…like in Codeigniter etc.

Leave a Reply

Your email address will not be published. Required fields are marked *