Jul
15
2010

An Easy Way to Display an RSS Feed with PHP

by   |  Posted in Tutorials  |  16 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(' & ', ' &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 it all together and this is what you get:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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(' & ', ' &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>';
	}
?>

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.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , , , , , , , , , ,

Short URL: http://bit.ly/cWQrqR

Discussion 16 Comments

  1. io on July 26, 2010 at 2:03 pm

    Thanks, it works great.

  2. thealphasite on August 1, 2010 at 4:41 am

    Excellent blog entry! Really useful! Keep it up

  3. tom on August 12, 2010 at 10:54 am

    Exaclty what I was looking for, thank you. I’ve used it to pull in a feed from an external website which has very flaky performance so I’ve added an if else statement to return an error message if the value of $feed if null

    load('http://www.informaworld.com/ampp/rss~content=t71610072');
    	$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("&", "&amp;", $feed[$x]["title"]);
    		$link = $feed[$x]["link"];
    		echo '<a href="'.$link.'" title="'.$title.'" rel="nofollow">'.$title.'</a>';
    	}
    ?>
  4. Davide on November 30, 2010 at 4:15 am

    Thanks in advance for providing the script and for the answer.
    How to limit the description text?
    Date is not displaying correct. How to fix?

  5. John on February 8, 2011 at 5:12 pm

    this is brilliant! – but I am a bit clueless… ummm how do I use my current style-sheet with this?

    Thanks again for the article

  6. John on February 9, 2011 at 5:49 am

    doah! sorted that one! (just put a link to the style sheet) but, now.. how do I get a link in the RSS to open in a new window? .. sigh..

    J

    • c.bavota on February 9, 2011 at 11:31 am

      Add a target="_blank" to the anchor tag.

  7. mOe3 on February 21, 2011 at 4:04 am

    hi
    nice job..sorry my english is low..

    i want show just 5 characters at feed description..

    —-how to limit characters to show description–
    echo ”.$description.”;

    tnx. im wait 4 answer

    • c.bavota on February 21, 2011 at 11:11 am

      This should do it:

      $description = explode(' ', $description, 5);
      $description = implode(" ",$description);
  8. mOe3 on February 22, 2011 at 3:11 am

    hi .tnx for answer ,
    i cant replace codes :(

    can u make make something for me? :)
    1- page encoding utf-8
    2- look this rss link http://www.cbi.ir/ExRatesRss.aspx = i want to show just first 5 number (or 5 character`s)

    i want like this demo
    http://453831.20upload.net/files/1389/bahman/Capturevbi.png
    yellow colored.

    thank you for helping me..

    $rss = new DOMDocument();
    $rss->load('http://www.cbi.ir/ExRatesRss.aspx');
    $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>'.$description.'</p>';
    }
    • c.bavota on February 22, 2011 at 11:37 am

      Add this right after the $description = $feed[$x]['link']; line.

      $description = substr($description, 0, 5);
  9. mOe3 on February 22, 2011 at 2:21 pm

    thank very much.
    i do with your great help thanks..

  10. Klaus on February 26, 2011 at 8:23 pm

    Hi,

    I have tried as well to add the
    $description = substr($description, 0, 5);
    line and it works fine to control the lenght of the description. However I would like that the last word get’s cut in the middle and also add the usual three dots at the end.
    What code lines should I add and where?

  11. Edgars on March 12, 2011 at 6:59 am

    hi, article is exelent, but i need to retrive this two elements to, one is img and one is price, but it dose not work for me,
    cant get this working corecly, can u sugest anything???

     
     
    18.00
  12. Lara on May 2, 2011 at 11:28 am

    Great post, thanks! I’ve added the code to my theme but a few people using it have run into this error:

    Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ‘)’ …

    on this line of code:

    'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,

    I can’t replicate the error. Someone on this thread suggested it might be a conflict with GoDaddy, but someone with 1&1 hosting reported the same issue. Any ideas? Thanks.

    • c.bavota on May 2, 2011 at 12:55 pm

      The issue is probably the server not having the proper libraries installed in PHP.