簡體   English   中英

如何使用PHP在XML文檔樹中選擇節點的第N個子節點?

[英]How Do I Select Nth-Child Of A Node In XML Document Tree With PHP?

考慮以下示例:

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

我想獲取值為“ 1,643”的“強”節點

我正在這樣做:

$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個強節點,如何選擇第三個強節點? 救命!

要獲取第三個<strong>節點,請執行以下操作:

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

因為索引從0開始。

如果xpath標題而不是位置選擇元素,請使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM