doujiaci7976 2014-07-26 09:14
浏览 31
已采纳

当数组为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.

  • 写回答

2条回答 默认 最新

  • doukang1962 2014-07-26 09:28
    关注
    $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";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算