duanpi2033 2012-03-29 03:19
浏览 67
已采纳

PHP:如何检查节点是否存在以及是否使用xpath?

I'm querying Alexa to get a given url's ranking. The return is in XML. Most times Alexa returns XML containing the REACH & RANK values, though sometimes it doesn't. When it doesn't, the code below that grabs the value for RANK throws an error:

Fatal error: Call to a member function xpath() on a non-object...

// Alexa Ranking
$url = 'http://data.alexa.com/data?cli=10&dat=s&url=' . $final_site;
$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_URL,$url); // set url to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 4); // times out after 4s
$result = curl_exec($ch); // run the whole process
$xml = simplexml_load_string($result);
//Get reach node
$popularity = $xml->xpath("//REACH"); // <-- ERROR OCCURS HERE
//Get the rank attribute
$alexa_rank = (string)$popularity[0]['RANK'];

Like I mentioned above, sometimes the xml tree looks like:

<ALEXA VER="0.9" URL="venturengine.com/" HOME="0" AID="=">
<SD TITLE="A" FLAGS="" HOST="venturengine.com">
<LINKSIN NUM="8"/>
</SD>
<SD>
<POPULARITY URL="venturengine.com/" TEXT="8709770"/>
<REACH RANK="8474566"/>
</SD>
</ALEXA>

and sometimes it looks like:

<ALEXA VER="0.9" URL="store.guldfors.nu/" HOME="0" AID="=">
<SD TITLE="A" FLAGS="" HOST="store.guldfors.nu"></SD>
</ALEXA>

which doesn't have the REACH or RANK nodes/attributes.

Is there anyway to wrap the xpath such as:

if($xml->xpath("//REACH") === TRUE) {
  //Get reach node
  $popularity = $xml->xpath("//REACH"); // <-- ERROR OCCURS HERE
  //Get the rank attribute
  $alexa_rank = (string)$popularity[0]['RANK'];
}

I've tried the above, doesn't work.

  • 写回答

1条回答

  • duan6301 2012-03-29 03:49
    关注

    I'm not sure of the exact syntax, but you might try counting the number of nodes in the target node set and seeing if it's greater than zero.

    For example, count(//Reach) > 0

    Another option appears to be to use boolean(//Reach)

    See xpath find if node exists

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题