How To Read an RSS File With PHP

I just got an email from one of our readers asking me to write a tutorial on how to parse an RSS with PHP, but the truth is I’ve already written one ( How to read XML with PHP ) . Just in case you did not know, an RSS feed is nothing more than an XML document.

All RSS feeds have the same components, they include the website’s information and entries or posts for a particular website, in the RSS document entries are referred to as “items”. Let’s take a look at what an RSS feed with two entries looks like.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<rss version="2.0">

<channel>
  <title>My Blog</title>
  <link>http://www.mydomain.com</link>
  <description>This blog is about blogging</description>
  <item>
    <title>How to install wordpress</title>
    <link>http://www.mydomain.com/how-to-install-wordpress/</link>
    <description>Learn to install WordPress in minutes</description>
  </item>
  <item>
    <title>How to install a wordpress theme</title>
    <link>http://www.mydomain.com/how-to-install-a-theme/</link>
    <description>Now that you've installed wordpress, change the default theme!</description>
  </item>
</channel>

</rss>

RSS documents can include more information than what you see above  but this is what they include for sure.

Now that we now what an RSS feed looks like let’s make a PHP script to read and show a feed using PHP’s simplexml.

$rssFeedUrl='http://somewebsite.com/feed.rss';
$rss=simplexml_load_file($rssFeedUrl);

// show site info

echo '<p>';
echo '<a href="'.$rss->channel->link.'">'.$rss->channel->title.'</a><br />';
echo $rss->channel->description;
echo '</p>';

// show posts

foreach($rss->channel->item as $post){
	echo '<p>';
	echo '<a href="'.$post->link.'">'.$post->title.'</a><br />';
	echo $post->description;
	echo '</p>';
}


There a many RSS-parsing PHP libraries out there with advanced features like caching, a popular one is SimplePie, but you should learn how to read XML files in general, this skill will help you work with a bunch of APIs including Twitter, Facebook, Amazon, BestBuy and all other popular websites that offer web services. Learn more about reading XML files in our series of XML with PHP posts.