如何从最后按顺序获取元素?
例如,我需要从最后获得第二项。
<?php
$html = <<<EOD
<div style="text-align: center;" class="navigation">
<span class="pagination">
<span>« novější</span> |
<span>1</span> |
<a href="?listType=&sort=&page=1">2</a> |
<a href="?listType=&sort=&page=2">3</a> |
<a href="?listType=&sort=&page=3">4</a> |
<a href="?listType=&sort=&page=1">starší »</a>
</span>
</div>
EOD;
$dom = PHPQuery::newDocument($html);
var_dump($dom->find('.navigation > .pagination > *')->eq(-2)->text());
var_dump($dom->find('.navigation > .pagination > *:last-child(2)')->text());
但不是4代码返回:
string(0) ""
string(11) "starší »"
答案 0 :(得分:0)
希望这会帮助你。在这里,我们使用DOMDocument
和DOMXPath
来获得所需的输出。
<?php
ini_set('display_errors', 1);
$html = <<<EOD
<div style="text-align: center;" class="navigation">
<span class="pagination">
<span>« novější</span> |
<span>1</span> |
<a href="?listType=&sort=&page=1">2</a> |
<a href="?listType=&sort=&page=2">3</a> |
<a href="?listType=&sort=&page=3">4</a> |
<a href="?listType=&sort=&page=1">starší »</a>
</span>
</div>
EOD;
$domObject= new DOMDocument();
$domObject->loadHTML($html);
$domQuery= new DOMXPath($domObject);
$results=$domQuery->query('//span[@class="pagination"]/a');
$contents=array();
foreach ($results as $result)
{
$contents[]=$result->textContent;
}
print_r(array_reverse($contents));
<强>输出:强>
Array
(
[0] => starší »
[1] => 4
[2] => 3
[3] => 2
)