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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。