Fetch RSS using PHP

RSS feeds are everywhere, and sometimes it’s a good idea to display one to keep people in the loop of important posts from your site, or sites you think might be relevant. Now, PHP 5 introduced the DOM extension which make it easy to work with XML documents. Now all it takes is just a small bit of code to fetch and display a feed.

The following code will first create a new DOMDocument() into which we will load the RSS feed.

load('http://randomhouseindia.wordpress.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 10;
if ($feed == null) echo "does not compute";
else
for($x=0;$x<$limit;$x++) { $title = str_replace("&", "&", $feed[$x]["title"]); $link = $feed[$x]["link"]; echo ''.$title.'
';
}
?>

This entry was posted in Development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Human Verification: In order to verify that you are a human and not a spam bot, please enter the answer into the following box below based on the instructions contained in the graphic.