Integrate Zend 2 XML writer into Yii

By Integrating the Zend 2.* framework into Yii you can quickly and painlessly generate XML outputs from your controllers. This will be helpful to anyone who has never done this before or only done it with Zend 1 as the introduction of namespaces can be strange when you first view them.

To start, you need to download the Zend Framework. Which one you download is up to you, I normally download the full package.

Once downloaded you need somewhere to put it. Within Yii, create a vendors folder. This should go in your protected folder.

Structure Protected/vendors/Zend

In my situation I wanted to output the XML from the controller for a sitemap.

public function actionZendXml(){

      // Generate Feed
}

The first thing we need to do is be able to reference the Zend framework. This is done with the following:

// load Zend	
	Yii::import('application.vendors.*');

	//Set alias path
	Yii::setPathOfAlias('Zend',Yii::getPathOfAlias('application.vendors.Zend'));

Now we need to collect your data for the XML sitemap.

$model = YourModel::model()->returnMyData(); // Or whatever your preferred method of collecting the data to use in your XML feed is

Now lets create the Feed object in Yii

// Create feed object
	$feed = new Zend\Feed\Writer\Feed;
	$feed->setTitle('My XML feed');
	$feed->setDescription('This is my awesome XML feed made with Zend 2');
	$feed->setLink('http://www.amazingXmlPage.com');
	$feed->setFeedLink($this->createUrl('site/ZendXml'), 'rss');
	$feed->setDateModified(time());

Now depending on the structure of your data we can create the entry for each part of the feed

// Create new item for RSS

	foreach ($model->getData() as $a) { 
		
		$entry = $feed->createEntry();
		$entry->setTitle($a->title);
		$entry->setLink($this->createUrl('controller/action', array('id'=>$a->id, 'title'=>$a->slug)));
		$entry->setDateModified(time($a->date_added));
		$entry->setDateCreated(time($a->date_modified));
		$entry->setDescription(strip_tags($a->description));
		
		$feed->addEntry($entry);
	
	}	

Now finally tell the controller to output the feed as raw XML

header("Content-type: text/xml");
	$out = $feed->export('rss');
	echo $out;

And that's it!

2 0
4 followers
Viewed: 8 150 times
Version: 1.1
Category: Tutorials
Tags: XML, zend
Written by: Jonny
Last updated by: CeBe
Created on: Feb 3, 2014
Last updated: 6 years ago
Update Article

Revisions

View all history

Related Articles