The SimplePie logo

If you need to load an RSS feed with the PHP programming language, the open source library SimplePie greatly simplifies the process of pulling in items from a feed to present on a website, store in a database or do something else coooool with the data. There's a full installation guide for SimplePie but you can skip it with just three steps:

  1. Download SimplePie 1.5.
  2. Copy the file autoloader.php and the folder library to a folder that's accessible from your PHP code.
  3. Make note of this folder; you'll be using require_once() to load autoloader.php from that location.

SimplePie has been designed to work the same regardless a feed's format. It supports RSS 2.0, RSS 1.0, Atom and the earlier versions of RSS. Additionally it can read feed elements from nine namespaces.

Here's PHP code that loads feed items from the news site Techdirt and displays them in HTML:

// load the SimplePie library
require_once('/var/www/libraries/simplepie-1.5/autoloader.php');

// load the feed
$feed = new SimplePie();
$feed->set_feed_url('https://www.techdirt.com/feed/');
$feed->init();
$feed->handle_content_type();

// create the output
$html_output = '';
foreach ($feed->get_items() as $item) {
  $html_output .= '<p><a href="' . $item->get_link() . '">' . $item->get_title() . '</a></p>';
  $html_output .= $item->get_description();
  $html_output .= '<p>By ' . $item->get_author(0)->get_name() . ', ' . $item->get_date();
}

// display the output
ECHO <<<END
$html_output
END;

The API documentation for SimplePie_Item lists the functions that can extract data from each feed item. The versatility of the library is demonstrated by get_authors(), which can retrieve an item's authorship information whether it was in the RSS author element, Dublin Core creator, iTunes author, or Atom author.

SimplePie supports caching so that a feed isn't downloaded every time code is executed. The addition of these lines turns on caching, specifies the location of a cache folder and sets the time to use a cached version to four hours (14,400 seconds):

$feed->set_cache_location('/var/www/cache/');
$feed->set_cache_duration(14400);
$feed->enable_cache();

SimplePie was created by RSS Advisory Board member Ryan Parman, Geoffrey Sneddon and Ryan McCue. The project is currently maintained on GitHub by Malcom Blaney.

Comments

:
:
:

Popular Pages on This Site