考虑以下示例:
<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个强节点,如何选择第三个节点? 救命啊!
答案 0 :(得分:1)
要获取第3个<strong>
节点,请执行以下操作:
$followers = $api->results->strong[2];
因为索引从0
开始。
如果要按标题而不是位置选择元素,请使用xpath
:
$followers = $api->xpath("//strong[@title = '1,643']")[0]; // with PHP >= 5.4
或使用PHP&lt; 5.4:
$followers = $api->xpath("//strong[@title = '1,643']");
$followers = $followers[0];
看到它有效:https://eval.in/128263