Friday, 4 October 2013

Display RSS Feed in your website with PHP

The following code will help you to easily integrate RSS feeds from another blog in your website:

In the first step we will create a DOM DOCUMENT into which we will load the rss feed.

$rss = new DOMDocument();
$rss->load('http://wordpress.org/news/feed/');    //Change this to the url you need.


Then from the array we will take out certain elements which we need to display in our site.


$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array ( 
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}


Now we set 5 posts to display initially. You can change the limit by changing the value of the $limit variable.

$limit = 5;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$date = date('l F d, Y', strtotime($feed[$x]['date']));
echo '<p><strong><a href="'.$link.'" title="'.$title.'">'.$title.'</a></strong><br />';
echo '<small><em>Posted on '.$date.'</em></small></p>';
echo '<p>'.$description.'</p>';
}


Put all this code together and you can see the RSS feeds displayed in your website :)

No comments:

Post a Comment