How to Read RSS Feeds using PHP


RSS feed is used to provide updates of blog or website for various platforms. We can use these feed to display as latest updates, news etc on our site. In this post I am explaining how to read rss feeds using php.

Let’s our rss feed url is http://demos.tricksofit.com/files/rss.php
Now we will read the content of the url using file_get_contents and store it in a variable called $content.
file_get_contents — Reads entire file into a string.

 
$url = "http://demos.tricksofit.com/files/rss.php";
$content = file_get_contents($url);

Now passing the $content to SimpleXmlElement, we will get the object representation of the content in $items variable.

 $items = new SimpleXmlElement($content);  

Finally we will go through the $items and get the information that we desire like as below:

echo "<ul>"; 
foreach($items->channel->item as $item) {  
	echo "<li><a href='$item->link' title='$item->title'>" . $item->title . "</a> - " . $item->description . "</li>";  
}  

echo "</ul>";  

Using foreach statement we cycle every item of the RSS and creats a variable called $item, that will contain each item tag in our RSS feed.

So the complete code will look like this:

function getFeeds($url){
	$content = file_get_contents($url);
	$items = new SimpleXmlElement($content);  

	echo "<ul>"; 
	foreach($items->channel->item as $item) {  
		echo "<li><a href='$item->link' title='$item->title'>" . $item->title . "</a></li>";  
	}  
	echo "</ul>";  
}

RSS feeds always follows the same basic structure, that the wonderful thing about it. Every feed contains “channel” as wraping tag. Then each post or entry in feed will be wrapped in “item” tag.

Reference:

Demo

How to Read RSS Feeds using PHP
How to Read RSS Feeds using PHP