A while ago I wanted a simple RSS feed parser, without the need of additional installations of libraries, plugins or scripts. I only wanted a simple function call and then print, for example, the latest blog posts in a sidebar or footer, preferably using PHP only. It turned out to be suprisingly difficult to find something this simple, so I decided to write my own. After assembling pieces and information from here and there I’ve written, and now sharing, a parser that fetches a RSS2.0 feed from a given URL and prints out the data. If you want it to work with Atom or RSS 1.0 feeds you may have to modify my code a little, but the basics are the same. The code requires PHP version 5, but you can find simplexml support for version 4. I’ve tested this code with WordPress feeds and feeds that meet the RSS2.0 standards.

This tutorial is targeted on people who are looking for something just as simple as this, or as a pointer for people who want to write their own and more advanced RSS parser. In this tutorial I assume that you know and understand some PHP beforehand, and this method is only one of many. This code really is as simple as it gets, it includes only the necessary things for a feed parser. There is no error handling or a support for incorrect RSS formats. I would also prefer if you read through the code and write it out yourself, not just copy-paste it. That way you can customize it to your liking, and you learn more.

PHP function to parse RSS2.0 feed

I’ve placed the parser code into a PHP function. Place this function in the beginning of your site’s files or even better, inside your functions.php if you have and use such a file. The function takes two arguments: the URL as a string and the number of posts to fetch as an integer, in that order. There is no error handling for wrong arguments, so be sure to get them right, or write your own error handling code.

This code extracts the RSS2.0 fields title, link, pubDate and description, but add or remove fields as you wish. As for data handling, the title and description is converted into ISO-8859-1 in order to fix special symbols (I’ve had issues with Norwegian symbols). The description field is then trimmed down to contain only the first 55 words, which you can change as you like. Take a look into PHP Strings to find out how to trim it down by the count of letters or sentences. The date and time format can also be customized, refer to the manual for PHP date to see how. I’ve marked the number of words and date/time format with a red underscore below.

<?php

function fetch_rss_feed($url, $numposts) {
			
     $rss = simplexml_load_file($url);  //Fetch RSS with simplexml
            
     $rss_array = array();
     foreach ($rss->channel->item as $item) {
          if ($numposts == 0) {
               break;
          } else {
               $link = (string) $item->link;  //Link to post
               $title = (string) $item->title;  //Title
    				
               //Convert title into ISO-8859-1 (solves special symbol problem)
               $title = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $title);		
    			
               //Get the date
               $pubdate = strtotime($item->pubDate);
               $propertime = gmdate('F jS Y, H:i', $pubdate);  //Customize this to your liking
    			
               //Description or post summary
               $desc = $item->description;
    				
               // turn URLs into hyperlinks
               $desc = preg_replace("/(http://)(.*?)/([w./&=?-,:;#_~%+]*)/", "<a href="\0">\0</a>", $desc);   
                    
               //Converts description into ISO-8859-1 (solves special symbols problem)
               $desc = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $desc);
                    
               //Shorten down description based on word count
               $shortdesc = ''; // Must be reset each time
               $token = strtok($desc, " ");
               $numwords = 55;  //The number of words
               $i = 0;
               while ($i < $numwords) {
                    if ($token != false) {
                         $shortdesc .= "$token ";
                         $token = strtok(" ");
                    }
                    $i++;
               }
                    
               //Adds a (...) at the end. Skip the next line if you don't want it
               $shortdesc .= " (...)";

               //Store into array
               $rss_item = array(
                    'title' => $title,
                    'date' => $propertime,
                    'link' => $link,
                    'descr' => $shortdesc
               );
               array_push($rss_array, $rss_item);

               $numposts--;
          }
     }
     //return array
     return $rss_array;
}
?>

If the feed contains less items than specified in the second argument, this function will not produce an error. Because we use foreach instead of a for loop to iterate, the code will stop iterating when there are no more items and return an array with the items it did found.

Printing out your feed data

When we have the above function available, all we need to do is to call it with two arguments: a string (feed URL) and an integer (number of items to fetch). The function returns an array with all our information, and we print out the data by iterating through the array. I’ve included an example of calling the function and iterating through the array below (your input is marked with a red underline). You can add any kind of HTML wrapping around the data, such as lists, div and/or span in order to control their positions and design through CSS. The example below utilizes unordered lists and span to differentiate the different kinds of data on each item.

<?php
//Runs function with feed url and number of posts as arguments
$my_rss = fetch_rss_feed('http://www.acornartwork.com/blog/feed', 5); 
?>

<ul class="rss-feed">
<?php foreach ($my_rss as $k => $v) : ?>
     <li>
     <span class="title"><a href="<?php echo $v['link']; ?>"  ><?php echo $v['title']; ?></a></span>
     <span class="date"><?php echo $v['date']; ?></span>
     <span class="descr"><?php echo $v['descr']; ?></span>
     </li>
<?php endforeach; ?>
</ul>

I hope this was useful in some way, please let me know if this doesn’t work for you. The code lacks error handling, such as checking the type of arguments and a timeout if the feed is unavailable, but I wanted to keep it as simple as possible in order to emphasize the skeleton that makes up for a pure PHP feed parser.

Share this post:
FacebookTwitterEmailShare