You are in: development / php development / zend framework / merge and order feed rss with zend framework

Create a kick-ass Feed RSS with Zend Framework

Here we go with a little tutorial about creating a oblique feed RSS over the Zend Framework using Zend_Feed, merging different feeds ( articles, products, whatsoever, ... ) and outputting them with the correct order.

First of all let's create the general array containing the description of our feed and the nested array which will contain our entries:

$feedArray = array (
                'title'             =>    'My RSS feed',
                'link'             =>    http://www.mysite.com,
                'language'      =>    'en-EN',
                'charset'        =>    'utf-8',
                'pubDate'      =>    time(),
                'entries'        =>    array()
            );

So now let's suppose we have lots of entities that we want to put in our feed, for example:

  • products
  • articles
  • comments on our posts
  • ...

We need to collect and put them into our $feedArray:

foreach ( $articles as $article ) {

                $date = new Zend_Date($article->created_time);

                $feedArray['entries'][] = array (
                        'title'            =>    $article->title,
                        'link'            =>    $article->link,
                        'guid'            =>    $article->link,
                        'description'    =>    $article->name,
                        'lastUpdate'    =>    $date->get(Zend_Date::TIMESTAMP)
                );

        }

the lastUpdate key will be used to determine the "published date" of your entity, so basically we're gonna use this param to order the entries.

The bad smell using this approach is that you'll put in youe entries first ALL the articles, then ALL the posts, then ALL the comments... Although you can decide the order of the articles, in your feed they will be shown ALWAYS before the other entities.

So we need to use usort() to determine a new order:

function sortFeedEntries($a, $b) {
            if ($a['lastUpdate'] == $b['lastUpdate']) {
                return 0;
            }
            return ($a['lastUpdate'] > $b['lastUpdate']) ? -1 : 1;
        }

    usort($feedArray['entries'], 'sortFeedEntries');

So now we can output our feed:

$feed = Zend_Feed::importArray($feedArray, 'rss');
$feed->send();
exit;

A good tutorial, which offered me lot to learn, is this one in the DevZone. Wink

Add your comment

Name:

E-mail:

URL:

Comment:

Emoticon:

"A bad open-source software can be improved, not thrown away.

A closed-source one can only be sent to the trash."