[英]How Do I Select Nth-Child Of A Node In XML Document Tree With PHP?
Consider the following example: 考虑以下示例:
<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>
I want to get that "strong" node with value of 1,643 我想获取值为“ 1,643”的“强”节点
I'm doing it like this: 我正在这样做:
$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;
}
But obviously, it returns error. 但是很明显,它返回错误。 There are 3 strong nodes, how do I select the third one? 有3个强节点,如何选择第三个强节点? Help! 救命!
To get the 3rd <strong>
node, do: 要获取第三个<strong>
节点,请执行以下操作:
$followers = $api->results->strong[2];
because indices start at 0
. 因为索引从0
开始。
If you want to select the element by its title instead of its position, use xpath
: 如果xpath
标题而不是位置选择元素,请使用xpath
:
$followers = $api->xpath("//strong[@title = '1,643']")[0]; // with PHP >= 5.4
or with PHP < 5.4: 或PHP <5.4以下:
$followers = $api->xpath("//strong[@title = '1,643']");
$followers = $followers[0];
see it working: https://eval.in/128263 看到它正常工作: https : //eval.in/128263
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.