2014-03-28 76 views
0

請看下面的例子:如何在使用PHP的XML文檔樹中選擇節點的第N個子節點?

<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng" yahoo:count="3" yahoo:created="2014-03-28T13:30:16Z" yahoo:lang="en-US"> 
<results> 
<strong class="js-mini-profile-stat" title="8">8</strong> 
<strong class="js-mini-profile-stat" title="0">0</strong> 
<strong class="js-mini-profile-stat" title="1,643">1,643</strong> 
</results> 
</query> 

我想是「強」與1643個

值點我做這樣的:

$tw=$_GET["tw"]; 

function twitter($tw) { 
$furl = file_get_contents("http://query.yahooapis.com/v1/public/yql?q=SELECT%20*%20from%20html%20where%20url=%22https://twitter.com/".$tw."%22%20AND%20xpath=%22//a[@class=%27js-nav%27]/strong%22&format=xml"); 

$api = simplexml_load_file($furl); 
$followers = $api->results->strong[3]; 
return $followers; 
} 

但很明顯,它返回錯誤。有3個強壯的節點,我如何選擇第三個節點? 幫助!

回答

1

來取得第三個<strong>節點,做到:

$followers = $api->results->strong[2]; 

因爲指數開始在0

如果您想選擇其標題來代替其位置的元素,使用xpath

$followers = $api->xpath("//strong[@title = '1,643']")[0]; // with PHP >= 5.4 

或PHP < 5.4:

$followers = $api->xpath("//strong[@title = '1,643']"); 
$followers = $followers[0]; 

看到它的工作:https://eval.in/128263

+0

謝謝。它正在工作。 – mehulmpt

相關問題