Workshop - week 06
Main Page >> Web Frameworks >> Web Frameworks - Workbook >> Workshop - week 06
Consuming an existing web feed
First you need to create a new controller, with just one "index" action.
In this action you simply create an instance of the Zend_Feed class, and call its "import" function to import a feed from a remote location (the BBC news website in this example). You then copy the content of the feed to an array, and pass the array to the view.
<?php // application/controllers/FeedController.php class FeedController extends Zend_Controller_Action { protected $_model; public function indexAction() { // Read remote feed try { $rss = Zend_Feed::import('http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/front_page/rss.xml'); } catch (Zend_Feed_Exception $e) { // feed import failed echo "Exception caught importing feed: {$e->getMessage()}\n"; exit; } // Initialize the channel data array $channel = array( 'title' => $rss->title(), 'link' => $rss->link(), 'description' => $rss->description(), 'items' => array() ); // Loop over each item and store relevant data foreach ($rss as $item) { $channel['items'][] = array( 'title' => $item->title(), 'link' => $item->link(), 'description' => $item->description() ); } // Pass to view $this->view->entries = $channel['items']; } }
You also need to create a view for your new controller/action.
<!-- application/views/scripts/feed/index.hhtml --> Feed Entries: <br /> <dl> <!-- Loop through the entries provided by the controller --> <? foreach ($this->entries as $entry): ?> <dt><?= $this->escape($entry['title']) ?></dt> <dd><?= $this->escape($entry['description']) ?></dd> <? endforeach ?> </dl>
You can then simply access your consumed feed at the following URL: http://mi-linux.wlv.ac.uk/~0123456/zend/public/feed/ (please replace 0123456 by your own student numbeer!)
Note: For simplicity and clarity we are importing the feed in the controller, but a feed is an XML file, and as such could (should?) be considered as a data source. In line with MVC principles it would therefore be better practice to move the feed import code to a "model" file.
Producing your own web feed
Let's create a new "feed" action in out existing "Guestbook" controller.
// application/controllers/GuestbookController.php public function feedAction() { // Change layout to blank.phtml (empty file) $this->_helper->layout->setLayout('blank'); // Set feed values $array['title'] = 'Guestbook feed'; $array['link'] = 'http://www.somewhere.com/'; $array['description'] = 'This is guestbook feed'; $array['charset'] = 'utf8'; // Loop through db records and add feed items to array $model = $this->_getModel(); foreach($model->fetchEntries() as $one_item) { $array['entries'][] = array( 'title' => $one_item['email'], 'link' => 'http://www.somewhere.com/123', 'description' => $one_item['comment'] ); } // Import rss feed from array $feed = Zend_Feed::importArray($array, 'rss'); // Send http headers and dump the feed $feed->send(); }