【问题标题】:PHP: How to check if a node exists and if not using xpath?PHP:如何检查节点是否存在以及是否不使用 xpath?
【发布时间】:2012-03-29 03:19:59
【问题描述】:

我正在查询 Alexa 以获取给定网址的排名。返回是 XML 格式的。大多数时候 Alexa 返回包含 REACH 和 RANK 值的 XML,但有时它不会。如果没有,下面获取 RANK 值的代码会引发错误:

致命错误:在非对象上调用成员函数 xpath()...

// 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'];

就像我上面提到的,有时 xml 树看起来像:

<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>

有时看起来像:

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

没有 REACH 或 RANK 节点/属性。

无论如何要包装xpath,例如:

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'];
}

上面的方法我试过了,还是不行。

【问题讨论】:

    标签: php xml xpath


    【解决方案1】:

    我不确定确切的语法,但您可以尝试计算目标节点集中的节点数,看看它是否大于零。

    例如count(//Reach) > 0

    另一个选项似乎是使用 boolean(//Reach)

    xpath find if node exists

    【讨论】:

    • 我尝试用以下内容包装获取节点部分以计算节点数:if(count($xml-&gt;xpath('//*') &gt; 2)) {},但它不起作用。语法可能只是错误,而不是想法。
    • 我不懂php。是否在对 xpath 的调用中包含对 count 的调用——例如,$xml->xpath("count(//*) > 2")——有效吗?
    猜你喜欢
    • 2012-08-30
    • 2010-10-20
    • 1970-01-01
    • 2015-04-14
    • 2017-06-03
    • 2015-04-29
    • 2012-03-26
    • 1970-01-01
    相关资源
    最近更新 更多