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 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色