How to Validate RSS Feed in PHP



RSS is now greate source of announcing new content of a Web site. RSS feeds are in XML format, but these feeds need to build with RSS specifications, so they can be executed well when any programs and sites that syndicate the feeds. We can there are some online tools to validate RSS feed like feedvalidator.org, validator.w3.org/feed/, rssboard.org/rss-validator/ etc, these tools checks if feed compliant with different version of RSS specification standards. In this article I am explaining how to validate RSS feed in PHP using feedvalidator.org in a simple way.

I have created a function validateFeed() which takes the feed url as parameter and return true if the feed is valid else it will return false.

function validateFeed( $rssFeedURL ) {
    $rssValidator = 'http://feedvalidator.org/check.cgi?url=';
		
    if( $rssValidationResponse = file_get_contents($rssValidator . urlencode($rssFeedURL)) ){
	if( stristr( $rssValidationResponse , 'This is a valid RSS feed' ) !== false ){
	    return true;
	} else {
	    return false;
	}
    } else {
	return false;
    }
}

Now we have a feed url http://www.tricksofit.com/feed and we need to pass it in the function as below.

 
$feedurl = "http://www.tricksofit.com/feed"; 
var_dump(validateFeed($feedurl));

In this function we don’t know how ‘feedvalidator.org’ validate the feed url. So I have created another function to validate RSS feed named validateRssFeed().

function validateRssFeed($feedurl){
	$content = file_get_contents($feedurl); 
	try {
	    $rss = new SimpleXmlElement($content); 
	    if(isset($rss->channel->item)){
		return true;
	    } else {
		return false;
	    }
	} catch(Exception $e){ 
		/* the data provided is not valid XML */ 
		return false; 
	}
}

We just need to pass the RSS feed url $feedurl to the function validateRssFeed() like as below.

 var_dump(validateRssFeed($feedurl)); 

It gets the content of $feedurl using file_get_contents and then gets the xml data object $rss using SimpleXmlElement, if it found any error in XML it goes in catch block and return false. Now function check if $rss contains item in it with $rss->channel->item, and it return true/false accordingly.

LIVE DEMO

How to Validate RSS Feed in PHP
How to Validate RSS Feed in PHP