Outputting JSON with Zend Framework

Today I was looking for a quick solution to outputting a response in JSON format from within one of my existing Zend_Controller actions that could be both requested and parsed using one of the jQuery Ajax methods.

The easiest method I could find was to use something similar to the following which first detects whether or not an XHTTP request has taken place, then outputs the response in plain text format.

if ($this->_request->isXmlHttpRequest()) {
	$content = array(
		'author' => 'Steve',
		'categories' => array(
			'PHP', 'Zend', 'JavaScript'
		)
	);
	$jsonData = Zend_Json::encode($content);
	$this->getResponse()
	->setHeader('Content-Type', 'text/html')
	->setBody($jsonData)
	->sendResponse();
	exit;
}

This will output only the encoded array (similar to that below) without including the page template.

{"author":"Steve","categories":["PHP","Zend","JavaScript"]}

It is essential that you exit the script after outputting the JSON, otherwise your page template will be rendered as well as outputting the encoded array and therefore removing the ability for it to be parsed correctly.

You should be aware that the isXmlHttpRequest method checks for an HTTP request header named X-Requested-With with the value ‘XMLHttpRequest’ and therefore may not work with all JavaScript libraries.

It does however work as expected with Prototype, Scriptaculous, Yahoo! UI Library, jQuery and MochiKit.

There are many alternative methods that could be used instead of this one, it’s just that I found this one to be the quickest and most simplistic method.

4 Replies to “Outputting JSON with Zend Framework”

  1. “It is essential that you exit the script after outputting the JSON”

    This is a big error. If you make a exit or die you prevent some methods to be working that may be important (like postDispatch) and other.

    If you dont want to use the template o the layout in some action only use:

    $this->_helper->layout->disableLayout();
    $this->_helper->viewRenderer->setNoRender();

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s