If you ever faced a scenario where you had to parse the rss feed with image thumbnails placed inside “enclosure” tags, SimplePie is the perfect solution. In fact SimplePie can parse mediaRSS. There are several other php classes such as Magpie which can do the job as well. Magpie can parse rss2.0 enclosure but not mediaRSS and I had hard time getting enclosure parsed with Magpie. After spending hours, I tried Simple Pie and it worked like a charm.
SimplePie is a fast and feature rich PHP class that is very simple to use.
In few steps, you can use SimplePie to retrieve and parse any RSS or Atom feeds and display them on any PHP website. SimplePie also allows you to incorporate any type of data from any number of feeds. Here’s how you can setup SimplePie in three steps:
- Download SimplePie and uncompress it
- Place the “simplepie.inc” into a your “includes” folder under root directory of your website and include it into your calling script
- Create a directory named “cache” (also in the web-accessible root directory) and make sure that it’s writable by the server (i.e., CHMOD to 755, 775, or 777)
Here’s the sample code to fetch, parse, cache, and display your external RSS and Atom feeds and mediaRSS on your website using SimplePie:
define('SIMPLEPIE', '/path/to/simplepie.inc');
require_once(SIMPLEPIE); //include the simplepie class
$url = 'https://www.parorrey.com/blog/feed/';
$feed = new SimplePie(); // bake a new pie
$feed->set_feed_url($url); // provide feed url
$feed->set_cache_duration (3600); // specify cache duration in seconds
$feed->handle_content_type(); // text/html utf-8 character encoding
$check = $feed->init(); // script initialization check
if ($check){
foreach ($feed->get_items() as $item) {
if ($enclosure = $item->get_enclosure())
$thumb = '';
else $thumb = '';
$rss_feed .= '
';
}
}
echo ''. $rss_feed .'';
SimplePie also allows you to merge different rss feeds into one single stream.
$feed = new SimplePie();
$feed->set_feed_url(array(
'http://your-domain1.com/your-feed1/',
'http://your-domain2.com/your-feed2/',
'http://your-domain3.com/your-feed3/'
));
Here is where the cache directory should exist if you are using the default cache location:
/path/to/your/feed_page.php
/path/to/your/cache/
/path/to/simplepie/way/deep/in/directory/simplepie.inc
Please note that using ./cache (dot-slash-cache) means that the cache directory will be relative to the page that’s calling SimplePie, not SimplePie itself.
Hope that helps.
Cheers!