November 12, 2009

Customize RSS Feeds with PHP

Filed under: PHP — admin @ 6:15 pm

Customize the display of your RSS feed using HTML and PHP. Starting with PHP version 5, SimpleXML loads, and parses an XML document. SimpleXML makes it easier to get access to xml content. Take a look at this simple example.


PHP provides a nice solution for inserting RSS feeds into an HTML document. Unlike previous XML implementations, SimpleXML uses the XML tag names as variables. If you need a refresher on the RSS 2.0 specification take a look at this site.

Here is the PHP code:

<?php
if (isset($_GET['category']))
  $rssfeed_category = (get_magic_quotes_gpc()) ? $_GET['category'] : addslashes($_GET['category']);
else
  $rssfeed_category = 'http://rss.news.yahoo.com/rss/topstories';
  libxml_use_internal_errors(true);
 
  if ($rssfeed = simplexml_load_file($rssfeed_category)) {
     foreach ($rssfeed->channel as $channel) {
        echo '<h2><a href="' . $channel->link . '">' .
				$channel->title . '</a></h2>';
        echo '<p>' . $channel->description . '</p>';
 
        foreach ($channel->item as $item) {
           echo '<div class="rssItem">';
           echo '<ul>';
           echo '<li><a href="' . $item->link . '" class="rssLink">';
           echo $item->title . '</a><br />';
           echo $item->description . '</li>';
           echo '</ul>';
           echo '</div>';
        }
   }
}
else echo 'RSS feed could not be read. ' . $rssfeed_category . '<br />';
?>

Tips to making this work:

  • Reserved HTML characters such as ampersand (&) and greater than(>) can cause problems if they appear as ordinary text in an XML document. The browser will mistake these reserved characters for markup. Use the php function htmlentities to convert characters such as & to &amp; if this becomes a problem.
  • Many RSS feeds contain HTML markup for formatting purposes. In this case, htmlentities is NOT recommened. Here’s an example of using htmlentities with description text containing HTML markup.
  • Character encoding can also lead to display problems. To ensure proper display of special characters, pay attention to the character encoding. UTF-8 is the default character encoding for XML. ISO-8859-1 is more commonly used in HMTL. If you use UTF-8 encoding in the HTML document’s head section, the special characters should print correctly.
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  • A file access warning from simplexml_load_file() may indicate a server warning. Check the php.ini configuration option allow_url_fopen = On. This will give the simplexml_load_file() function the ability to open the remote rss file. However it will not be good for website security because it leads to PHP Remote File Include Hacks.
  • RELATED POSTS:

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress