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