Retrieve and display rss with php

Needed a simple script to test out RSS handling in php. This one worked (which is more than I can say for many I tried).

From, a really simple script to retrieve and display rss feeds using php.

This requires the DOM extension included with php since version 5.2 be loaded. You also need to enable allow_url_fopen in /etc/php.ini (or wherever your php.ini is.

allow_url_fopen = On

I named the script “getrss.php”.

$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&lt;$limit;$x++) {
   $title = str_replace(' &amp; ', ' &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>';

The rss feed url is defined in $rss->load, and the number of posts to retrive in “$limit”.

There’s also a very good article on php and rss over at IBM Developerworks, PHP and RSS: Getting it together.