Using PHP to Include RSS Feeds

Raven

Using PHP to Include RSS Feeds

We needed some code to include RSS feeds on our web site. I quickly found Magpie RSS, which is a PHP library for fetching, parsing, and even caching feeds.

MagpieRSS is compatible with RSS 0.9 through RSS 1.0. Also parses RSS 1.0′s modules, RSS 2.0, and Atom. (with a few exceptions)

Jon wanted the function to allow for different numbers of posts and varying lengths of text. To handle the number of posts and the formatting, and to make this easy to integrate, I created this function:

function print_rss($url,$count=2,$length=150) {
  require_once('magpierss/rss_fetch.inc');
  require_once('smart_trim.php');
  $rss = fetch_rss($url);
  foreach ($rss->items as $item) {
    if (++$cnt>$count) { break; }
    $href = $item['link'];
    $title = $item['title'];
    $published = strtotime($item['pubdate']);
    $content = strip_tags($item['content']['encoded']);
    $body = smart_trim($content, $length, false, '...');
    echo '<p>';
    echo '<span style="font-size: 80%;color:#9BB23B;">';
    echo date('F d, Y', $published);
    echo '</span><br />';
    echo "<a href=\"$href\">$title</a><br />";
    echo '<span style="font-size:80%;color:#666;">';
    echo $body;
    echo "<br /><a href=\"$href\">More &#187;</a></span>";
    echo '</p>';
  }
}

I put this function in a file called main.inc, and put that in our incs directory, along with the directory for MagpieRSS. I also grabbed a library for trimming text without breaking up words, which I found here. Just download the zip file and put smart_trim.php in the same directory with main.inc. The directory listing should look like this:

/www/index.php
/www/incs/
/www/incs/main.inc
/www/incs/smart_trim.php
/www/incs/magpierss/
/www/incs/magpierss/rss_cache.inc
/www/incs/magpierss/rss_fetch.inc
/www/incs/magpierss/rss_parse.inc
/www/incs/magpierss/rss_utils.inc
/www/incs/magpierss/extlib/Snoopy.class.inc

If the web server has write permissions, MagpieRSS will create a cache directory where it will keep a copy of the feeds until there is new content to grab. On our server, it created it as /cache.

Finally, to add this to a web page we use this code:

require_once('incs/main.inc');
print_rss('http://raventools.com/blog/?feed=rss2',2,200);

This gives us the latest 2 posts, with up to 200 characters of content as a teaser.

Comments are closed on this post