Simple way to Display an RSS Feed with PHP


RSS Feed with PHP

There is always that one time you need to display an RSS feed on another part of the site, or even on a different site completely. Thankfully PHP 5 makes it easy to work with RSS feeds by using the DOM extension. All it takes is about 30 seconds of code with this Simple way to Display an RSS Feed with PHP

First we create a new DOM object, which we will load the our own RSS feed.

$rss = new DOMDocument();
$rss->load('http://westcoastmarketing.ca/feed/');

Then we set an array and push the variables we want from the RSS feed, into the array.

$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,
		);
	array_push($feed, $item);
}

Then we set the number of articles to display at 10, and link the title to the original article.

$limit = 10;
for($n=0;$x<$limit;$n++) {
	$title = str_replace(' & ', ' &amp; ', $feed[$n]['title']);
	$link = $feed[$n]['link'];
	$description = $feed[$n]['desc'];
	echo '<p><b><a href="'.$link.'" title="'.$title.'">'.$title.'</a></b><br />';
	echo '<p>'.$description.'</p>';
}

Its all really quite easy to set up. Try it on your own server!

And, here is the final code.

<?
$rss = new DOMDocument();
$rss->load('http://westcoastmarketing.ca/feed/'); // Set the blog RSS feed url here

$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,
		);
	array_push($feed, $item);
}


$limit = 10; // Set the number of articles to load here
for($n=0;$x<$limit;$n++) {
	$title = str_replace(' & ', ' &amp; ', $feed[$n]['title']);
	$link = $feed[$n]['link'];
	$description = $feed[$n]['desc'];
	echo '<p><b><a href="'.$link.'" title="'.$title.'">'.$title.'</a></b><br />';
	echo '<p>'.$description.'</p>';
}

?>

If you use this. let me know in the comments below! Enjoy!

7 Comments

    • I thought I’d have to read a book for a discovery like this!

      Post a Reply
  1. 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.

    Post a Reply
  2. Yeah for Pinterest! Like I needed an excuse to do this. Thanks for all of your great articles. I am just beginning this online business adventure and your website is so very helpful.

    Post a Reply

Submit a Comment

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