Creating an RSS File With PHP

Saturday, March 21, 2009

RSS is a specific XML format that has been created for the sole purpose of syndicating "news" type information. It considers your information to be a channel and for that channel to have multiple items. Each item in turn caan have certain information included, such as a title, URL, and description. RSS is used regularly now by news websites, blogs, and podcasts.

For full specification, you can visit http://www.rssboard.org/, which hosts the current keepers of the standard. As an example, the code below generates a small RSS feed from an array of news items.

<?php
// Create our array of news stories.
// These might have come from a database originally:
$news = array(
  array('Man hates politics', 'http://example.com/23423.php',
    'A man has been found that hates politics.  Politicians are surprised.'),
  array('Cat eats mouse', 'http://example.com/83482.php',
    'A cat was found eating a mouse.  The mouse was very surprised.'),
  array('Programmer gets hired', 'http://example.com/03912.php',
    'A programmer has received a telecommuting agreement, and is happy.'),
    );

// Now, first to create our RSS feed, start with the appropriate header:
header('Content-type: text/xml');

// Echo out the opening of the RSS document.  These are parts that just
//  describe your website, and what the RSS feed is about:
echo '<?xml version="1.0" ?>';
echo <<<EORSS

<rss version="2.0">
  <channel>
    <title>Not So Nifty News Stories (NSNNS)</title>
    <link>http://example.com/nsnns.php</link>
    <description>The best news stories we can legally find!</description>
    <language>en-us</language>
    <copyright>Copyright 2006 - NSNNS</copyright>
    <webMaster>webmaster@example.com</webMaster>
    <generator>A Custom PHP Script</generator>
EORSS;

// Now that we've taken care of that, we can echo out each news item
// So just start looping through them!
foreach ($news as $item) {
    // Well, not much fancyness needed, just echo them out:
    echo <<<EOITEM

    <item>
      <title>{$item[0]}</title>
      <link>{$item[1]}</link>
      <description>{$item[2]}</description>
    </item>
EOITEM;
}

// Almost done.  Just need to print a few closing tags now and that's it:
echo <<<EOCLOSE

  </channel>
</rss>
EOCLOSE;
?>


As can be seen from examining the code, this script starts off with some data. In this case an array of data refers to various news stories including a title, a URL, and a description of the story. Using this data, it generates an RSS feed that describes all of this news. The data more likely would have come from a database in a real example.

Hope it helps.

0 comments: