0
我在查询Alexa以获得给定的网址排名。返回是以XML格式。大多数时候Alexa返回包含REACH & RANK值的XML,尽管有时并不是这样。当它不,下面的代码为抓住RANK值抛出一个错误:PHP:如何检查节点是否存在,如果不使用xpath?
致命错误:调用一个成员函数的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'];
}
我已经试过以上,不能正常工作。
我试图包装用的get节点部下面来计算节点的数量:'if(count($ xml-> xpath('// *')> 2)){}'并且它不起作用。虽然语法可能是错误的,但不是这个想法。 – 2012-03-29 15:59:45
我不知道PHP。在xpath调用中包括调用计数 - 例如$ xml-> xpath(“count(// *)> 2”) - 是否工作? – Steve 2012-03-29 20:20:37