【发布时间】: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'];
}
上面的方法我试过了,还是不行。
【问题讨论】: