LanguagesCreating RSS Feeds with the Zend Framework for Fun and Profit

Creating RSS Feeds with the Zend Framework for Fun and Profit

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Over the past few years, I’ve shown you how to build custom RSS aggregators using PHP and MySQL and Ruby. Even five years after penning the former tutorial, RSS is going as strong as ever, depended upon by millions of users around the globe to keep track of an increasingly diverse array of online information. For instance, back in that 2004 tutorial I praised websites such as Yahoo!, CNET, and The Christian Science Monitor for their efforts to bring RSS to a larger population. Five years later, RSS feeds have become as commonplace as contact forms, and in fact their application has expanded to reading email, keeping tabs on the weather, and following your friends on Twitter. So, if you haven’t already taken steps to integrate RSS feeds into your website, what’s stopping you? You’re not only denying your existing users a great mechanism for keeping tabs on your website’s latest updates, but are potentially hindering audience growth by turning visitors insistent on cutting down on tedious repeat visitations to countless websites.

Still not convinced? What if I told you there’s not only an incredibly easy way to build RSS feeds from your custom data, but also about a great solution for making money by integrating advertising directly into these feeds? By using the Zend Framework and Google AdSense, accomplishing both tasks is frighteningly easy. In this tutorial, I’ll show you how.

Creating Custom Feeds with the Zend Framework

As you’ve seen in previous tutorials, the Zend Framework (see Twitter, internationalization, Amazon Web Services, and OpenID Authentication tutorials) offers Web developers a tremendously powerful solution not only for building maintainable websites, but also for taking advantage of the latest web services. This offering includes the Zend_Feed component, which makes it incredibly easy to both build and consume RSS feeds.

For instance, I use Zend_Feed in conjunction with regularly executing cron job to create and RSS feed highlighting the 25 most popular video games according to Amazon.com sales. Using wget and HTTP authentication, every six hours the cron job executes, using curl to contact a URL that triggers the building of an updated RSS feed. The crontab entry looks like this:

0 0,6,12,18 * * * /usr/bin/curl --user webuser:supersecret
   --silent http://www.gamenomad.com/cronjobs/populargames

This entry tells cron to execute every day of every month at 12am, 6am, 12pm, and 6pm, using the curl program to contact the provided GameNomad URL. Because I don’t want just anybody contacting this URL, it’s password-protected. Authentication occurs using curl’s –user option. See Wikipedia’s cron entry for more information about cron and crontab.

The populargames action found in the cronjobs controller is presented next; it takes advantage of the Zend_Feed component to build the feed based on information stored in the website’s MySQL database. Rather than exhaustively guide you through every line of the action, I’ve included line numbers alongside the code, and will follow the listing with a breakdown of key lines.

01 public function populargamesAction()
02 {
03 
04     // Create array to store the RSS feed entries
05     $entries = array();
06     
07     // Retrieve the 25 most popular games
08     $game = new Game();
09     $rankings = $game->getLatestSalesRanks(25);
10     
11     // Cycle through the rankings, creating an array storing
12     // each, and push the array onto the $entries array
13     foreach ($rankings AS $ranking) {
14         $entry = array(
15           'title'       => "{$ranking->title}
                              ({$ranking->platform})",
16           'link'        => "http://www.gamenomad.com/games/
                               {$ranking->asin}",
17           'description' => "Sales Rank: #{$ranking->rank}",
18         );
19         array_push($entries, $entry);
20     }
21     
22     // Create the RSS array
23     $rss = array(
24       'title'   => 'GameNomad: Popular Games',
25       'link'    => 'http://www.gamenomad.com/games/ranks',
26       'charset' => 'ISO-8859-1',
27       'entries' => $entries
28     );
29     
30     // Import the array
31     $feed = Zend_Feed::importArray($rss, 'rss');
32     
33     // Write the feed to a variable
34     $rssFeed = $feed->saveXML();
35     
36     // Write the feed to a file residing in /public/rss
37     $fh = fopen($this->config->feed->popular_games, "w");
38     fwrite($fh, $rssFeed);
39     fclose($fh);
40     
41 }

If you’re even moderately familiar with the Zend Framework, much of this should be quite familiar, save for the Zend_Feed-specific calls. Now, review key lines in this listing:

  • Line 09: Retrieve an array consisting of the top 25 sales ranks, using a method defined within the Game model.
  • Lines 13-20: Cycle through the array, creating an associative array consisting of each game’s title, platform, GameNomad URL, and latest sales rank. Line 19 will push this array onto another array, which will contain each newly created associative array.
  • Lines 23-27: Define the RSS feeds title, URL, and character set.
  • Line 28: Assign the $entries array to the entries index of the $rss array, which will result in each element of the $entries array being defined as an RSS item.
  • Line 31: Generate the RSS feed.
  • Line 34: Save the feed to a variable.
  • Lines 37-39: Write the feed to a publicly-accessible file.

Incidentally, you can access this feed by navigating to the following location:

http://www.gamenomad.com/rss/populargames.xml

If you load this feed into Google Reader, you’ll see output similar to that shown in Figure 1.

Figure 1: Viewing an RSS Feed from Google Reader

Integrating Feed Ads with Google AdSense for Feeds

So, you’ve created the RSS feed and have started letting your friends know about it. Now what? It’s time to make some money!

I believe Google’s advertising network for website publishers, known as AdSense, has rocketed to popularity due to three key characteristics: first, there’s no barrier-to-entry; that is, you can join the program at no charge no matter how large or small your website happens to be. Second, the advertisements served to your website are targeted to your audience. That is, if you’re running a website for video game enthusiasts, you can expect advertisements focused around gaming gear, science fiction, and other topics likely to interest your users, thereby increasing the likelihood the advertisements will have some direct appeal. Finally, the advertisements are non-intrusive; you won’t find any wildly annoying popups, spyware, or similar ads intended to hinder the user’s browsing experience.

Apparently, millions of other website publishers agree with this sentiment; since the program’s launch in 2003, it has easily become the largest online advertising network on the planet, and has since branched into mobile, radio, and television advertising. In 2005, AdSense launched another great service, known as Google AdSense for Feeds. AdSense for Feeds makes it easy for you to generate revenue through your RSS feeds by integrating context-specific text-based advertising into your feed content. Further, true to the AdSense ethos, you’ll maintain complete control over the process, dictating the insertion frequency, insertion position, and circumstances in which ads are inserted (based on post word count).

If you haven’t already signed up for Google AdSense, head over to http://www.google.com/adsense/ and register. The vetting process is a bit more involved than what you might be used to when registering for online services, because Google will actually review the website you’ve identified as being the advertising location to ensure it meets the terms set forth in its program policy. Once your account has been approved (in my experience, this has taken less than 24 hours; however, Google indicates the process could occasionally take several days), you can begin taking advantage of AdSense.

Creating an Advertising-Aware RSS Feed

The beauty of AdSense for Feeds is that it doesn’t require you to refactor any of the code you created at the beginning of this tutorial. All you need to do is provide Google with the existing feed’s URL, and it will create a new FeedBurner-hosted URL, thereby providing you not only with the ability to generate revenue through the feed advertising, but also granting you all of the great traffic analysis tools made available through this great service (incidentally, FeedBurner was purchased by Google in late 2007, although it continues to run seemingly autonomously, albeit with enhanced integration into Google’s array of online services). If you already host your feeds on FeedBurner, you’ll soon see there’s an easy way to import the feeds into AdSense for Feeds.

To integrate AdSense into your existing RSS feed, login to AdSense at http://www.google.com/adsense/ and navigate to AdSense Setup > Get Ads. From there, you’ll be able to choose from the six available AdSense products, among them AdSense for Feeds. Click on the appropriate link and you’ll next be prompted to generate an advertising-infused feed. You’ll see numerous creation options, including the ad type (text-only, images-only, or a mix of both), appearance frequency, position, and even identify preferred design colors. You can also assign the feed to an AdSense channel. However, the most important part of this creation process is located at the conclusion (see Figure 2), where you’ll map the feed to AdSense. Click the Burn new feed link, and in the window that appears, paste in your feed URL.

Figure 2: Mapping Your RSS Feed to Google AdSense for Feeds

Once AdSense confirms an RSS is found at the other end of the provided URL, it will prompt you to provide a custom address and title, and ask you to confirm whether you’d like FeedBurner to track subscriber statistics (see Figure 3).

Figure 3: Pointing Google to Your RSS Feed

All that’s left to do is replace the previously published feed URL with your new one, and begin reaping the rewards of advertising revenues!

Where to From Here?

In a world where users have come to expect data to be consumable from any location and device, RSS provides an invaluable service to website owners seeking to expand their audience. Check out these links for more information about RSS, the Zend_Feed component, and Google’s AdSense for Feeds product!

  • The Wikipedia RSS entry: Not surprisingly, Wikipedia offers one of the best-written RSS definitions you’ll find anywhere on the Web. Check it out if you’d like to learn more about the history of this popular format.
  • The Zend_Feed documentation: The Zend Framework’s Zend_Feed documentation shows you not only how to create RSS feeds, but consume them as well.
  • AdSense for Feeds: Learn more about how to get started using Google’s AdSense for Feeds product via the excellent product documentation.

About the Author

Jason Gilmore is founder of W.J. Gilmore, LLC, a publishing and consulting firm based out of Columbus, Ohio. Formerly Apress’ open source editor, Jason fostered the development of more than 60 books, along the way helping to transform their open source line into one of the industry’s most respected publishing programs. He’s the author of several books, including the best-selling Beginning PHP and MySQL: From Novice to Professional (currently in its third edition), Beginning PHP and PostgreSQL: From Novice to Professional, and Beginning PHP and Oracle: From Novice to Professional.

Jason is cofounder of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer’s conference.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories