How can I get element by order from the end?
For example, I need to get second item from the end.
<?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());
But instead of 4 this code returns:
string(0) ""
string(11) "starší »"
Hope this will help you out. Here we are using DOMDocument
and DOMXPath
to get the desired output.
<?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));
Output:
Array
(
[0] => starší »
[1] => 4
[2] => 3
[3] => 2
)