Using SimplePie to parse RSS

May 8th, 2006 by Sarah King

Cake PHP have launched a new version or their PHP framework and one of the snippets was the integration of SimplePie. The install and demo for normal sites is incredibly simple and the code is fully featured but held in a single file. It can even spit out the "subscribe via" links for the major sites.

All in all it appears to be very impressive.

  1. Unzip the files on your local file system and run the demo and make sure everything is setup ok. Don't be alarmed by the huge logo, you are still on your own site ;)
  2. If you want to skip the demo the only file you actually need is simplepie.inc
  3. create this function in your script
    PHP:
    1. function getSimplePie($url)
    2. {
    3.    include('simplepie/simplepie.inc');
    4.    // Parse it
    5.    $feed = new SimplePie();
    6.    $feed->feed_url($url);
    7.    $feed->cache_location('./../cache');
    8.    $feed->init();
    9.    
    10.    if ($feed->data)
    11.    {   
    12.       $output = "<table cellspacing='0' cellpadding='0'>
    13.       <tr><th valign='top'>
    14.       <a href=" . $feed->get_feed_link() . ">"
    15.       .$feed->get_feed_title()
    16.       ."</a> - ".$feed->get_feed_description()
    17.       ."</th></tr>";
    18.    
    19.       $max = min(5, $feed->get_item_quantity());
    20.       for ($x = 0; $x <$max; $x++)
    21.       {
    22.          $output .= "<tr>
    23.          <td>
    24.          <a href='" . $feed->get_item_permalink($x) . "'>"
    25.          .$feed->get_item_title($x)
    26.          ."</a>
    27.          </td>\n";
    28.       }
    29.    }
    30.    $output .= "</table>";   
    31.    return $output;
    32. }//getSimplePie

  4. You can now echo getSimplePie and pass in the feed address from anywhere in your page.
Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Twitter
  • StumbleUpon
  • Mixx
  • Google Bookmarks
  • Blogplay
  • Add to favorites
  • Sphinn
  • NewsVine
  • Propeller
  • Yahoo! Bookmarks
  • Yahoo! Buzz

9 Responses to “Using SimplePie to parse RSS”

  1. Where is the CakePHP SimplePie snippet? I just can’t find it.

  2. EJ Fox says:

    Why the tables? :(

  3. sarahk says:

    In the example? That’s just a hangover from the original test. I’d use a list normally.

  4. Ashley says:

    How do i echo getsimplepie?

  5. Sarah King says:

    just

    [php]echo getSimplePie(‘http://mysite.com/feed/’);[/php]

  6. obay says:

    is there a way to include more than one rss feed?

  7. Sarah King says:

    No, but you can get several feeds – build them into an array, sort and output.

Leave a Reply

You must be logged in to post a comment.