Search code examples
phpxpathdomxpath

Get last li content Xpath php


I have next html:

<ul class="pages">
<li class="page-1 active"><a data-page="1" href="/sold?page=1">1</a></li>
<li class="page-2"><a data-page="2" href="/sold?page=2">2</a></li>
<li class="page-3"><a data-page="3" href="/sold?page=3">3</a></li>
<li>...</li>
<li class="page-975"><a data-page="975" href="/sold?page=975">975</a></li>
</ul>

I am trying to get the last li's text which contains the number of the last page (in my example it is 975) with help of Xpath.

I've tried something like:

$page_count = $xpath->query(".//ul[@class='pages']/li/a[last()]/text()")->item(0)->textContent;

but it doesn't work.

what would be the correct query to get last li's text?


Solution

  • try this one:

    $page_count = $xpath->query(".//ul[@class='pages']/li[last()]/a/text()")->item(0)->nodeValue;
    

    first: you need to grab the last li and then the text of its a-element

    Your version basically searches all the li-elements and within them searches for the last a-element (they only have one) and then their text attribute. So you basically got a list of all the texts.

    second: try nodeValue instead of textContent