当数组为null时,PHP没有对象错误

I have a RSS feed URL and I am using following PHP function to extract values from it.

$xml = simplexml_load_file($url);

Its working perfect when the $url generates some results. And I am using count() function to count the length of array thats extracted from RSS feeds.

$length=sizeof($xml->rs[0]->r);

But when there is no result in RSS it gives me error

Trying to get property of non-object in /home/****/public_html/index.php on line 5 

So is there a way to echo a message if there are no results in RSS feed URL.

And when i do print_r($xml) ob no results $xml , i get

SimpleXMLElement Object ( [@attributes] => Array ( [type] => noresults [code] => 1.1 ) [title] => SimpleXMLElement Object ( ) [subtitle] => SimpleXMLElement Object ( ) [text] => SimpleXMLElement Object ( ) [base] => SimpleXMLElement Object ( ) ) )

I searched everywhere and found no solution.. Thanks for your help.

$xml = simplexml_load_file($url);

if ($xml && property_exists($xml, 'rs') && is_array($xml->rs) && isset($xml->rs[0]) && is_object($xml->rs[0]) && property_exists($xml->rs[0], 'r')) {
    // do something with $xml->rs[0]->r
} else {
    echo "Not available to access $xml->rs[0]->r";
}

You can do this:

if(is_a($xml,"SimpleXMLElement"))
{
    //process XML here
}
else
{
    die("Unable to load XML from URL");
}

The is_a function takes two arguments - the first is an object variable and the second is the class to which we are checking if it belongs to.

Based on the update to your question it looks like you are getting an XML object returned by the service irrespective of whether there are results or not. In that case you need to examine the returned XML in order to check if it has value or is saying that there are no results.

Pay attention to the return value ( [@attributes] => Array ( [type] => noresults [code] => 1.1 )

You can use SimpleXMLElement::attributes function to loop and example attributes. Everything you need to test it out is documented pretty well in the PHP Manual for SimpleXMLElement