如何使用PHPQuery从最终获取元素?

时间:2017-05-05 18:21:06

标签: php parsing phpquery

如何从最后按顺序获取元素?

例如,我需要从最后获得第二项。

<?php
  $html = <<<EOD
<div style="text-align: center;" class="navigation">
        <span class="pagination">
          <span>« novější</span> | 
          <span>1</span> | 
          <a href="?listType=&amp;sort=&amp;page=1">2</a> | 
          <a href="?listType=&amp;sort=&amp;page=2">3</a> | 
          <a href="?listType=&amp;sort=&amp;page=3">4</a> | 
          <a href="?listType=&amp;sort=&amp;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ší »"

1 个答案:

答案 0 :(得分:0)

希望这会帮助你。在这里,我们使用DOMDocumentDOMXPath来获得所需的输出。

<?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=&amp;sort=&amp;page=1">2</a> | 
          <a href="?listType=&amp;sort=&amp;page=2">3</a> | 
          <a href="?listType=&amp;sort=&amp;page=3">4</a> | 
          <a href="?listType=&amp;sort=&amp;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
)