Outputting results in different formats with ZF

So no doubt somewhere on your site, you’ll have a page displaying a list of items or whatnot. In this example it’s a search results page.
We’ll have a controller action with a corresponding view (in my case its the searchAction() )
We have a view file that uses HTML markup with a PHP foreach loop to iterate through each row in the result.

But who says we want HTML? We could equally be asking for XML, JSON, CSV, anything!

This is where Zend Framework’s context switcher comes into use. It’s really simple!

In your init() method of your controller class, use something like this:

public function init()
         // initialize context switch helper
         $contextSwitch = $this->_helper->getHelper('contextSwitch');
         $contextSwitch->addActionContext('search', 'xml')

This allows us to use the URL parameter ?format=xml or /format/xml
We need a different view instead of search.phtml, so create search.xml.phtml

// create XML document 
$dom = new DOMDocument('1.0', 'utf-8');   
// create root element 
$root = $dom->createElementNS( 'http://yoursite, 'del:document'); 
// convert to SimpleXML 
$xml = simplexml_import_dom($dom);   
// add summary element 
$xml->addChild('matches', count($this->results)); 
$xml->addChild('searchTime', time());   
// add resultset elements 

$results = $xml->addChild('results'); 
foreach ($this->results as $r) 
$result = $results->addChild('result');   
$result->addChild('id', $this->escape($r->id));   
$result->addChild('name', $this->escape($r->name));   
$result->addChild('age', $this->escape($r->age));   
$result->addChild('height', $this->escape($r->height));   
$result->addChild('country', $this->escape($r->Country));   
$skills = $result->addChild('skills');   
$skills->addChild('primary', $this->escape($r->primary));
$skills->addChild('secondary', $this->escape($r->secondary)); 
// return output
 echo $xml->asXML();

Now we can browse to /index/search or /index/search/format/xml and get our results displayed in a custom format! Nose in to the Zend Docs to find out more! 😀


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 )


Connecting to %s