An Easy Way to Display an RSS Feed with PHP
by Bandicoot Marketing on | Posted in Tutorials | 18 comments
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. Luckily, 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 WordPress.org RSS feed.
$rss = new DOMDocument(); $rss->load('http://wordpress.org/news/feed/');
Then we will single out certain elements and place them into an array. For this example, I will just fetch the title, description, link and published on date.
$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); }
Finally, we set it to display 5 posts on screen with the titles linking directly to the original post.
$limit = 5; for($x=0;$x<$limit;$x++) { $title = str_replace(' & ', ' & ', $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 it all together and this is what you get:
<?php $rss = new DOMDocument(); $rss->load('http://wordpress.org/news/feed/'); $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); } $limit = 5; for($x=0;$x<$limit;$x++) { $title = str_replace(' & ', ' & ', $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>'; } ?>
Not too complicated. All you need to change is the feed you want to load (line #3) and the number of posts to display (line #14). Of course, you could always play around with the output to get it styled exactly how you want. That is totally up to you.
18 comments for “An Easy Way to Display an RSS Feed with PHP”