Vous pouvez utiliser PHP's DOM module pour cela. Lisez la page avec DOMDocument :: loadhtmlfile(), puis créez un objet DOMXPath et interrogez tous les éléments span du document ayant l'attribut class = "page-numbers".
(edit: oups, pas ce que vous cherchez, voir le deuxième extrait de code)
$html = '<html><head><title>:::</title></head><body>
<div class="pager">
<span class="page-numbers current">1</span>
<a href="/users?page=2" title="go to page 2"><span class="page-numbers">2</span></a>
<a href="/users?page=3" title="go to page 3"><span class="page-numbers">3</span></a>
<a href="/users?page=4" title="go to page 4"><span class="page-numbers">4</span></a>
<a href="/users?page=5" title="go to page 5"><span class="page-numbers">5</span></a>
<span class="page-numbers dots">…</span>
<a href="/users?page=15" title="go to page 15"><span class="page-numbers">15</span></a>
<a href="/users?page=2" title="go to page 2"><span class="page-numbers next"> next</span></a>
</div>
</body></html>';
$doc = new DOMDocument;
// since the content "is already here" we use loadhtml(content)
// instead of loadhtmlfile(url)
$doc->loadhtml($html);
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query('//span[@class="page-numbers"]');
echo 'there are ', $nodelist->length, ' span elements having class="page-numbers"';
modifier: Cette
<a href="/users?page=15" title="go to page 15"><span class="page-numbers">15</span></a>
(le second dernier élément a
) toujours le point à la dernière page, c.-à-d. ce lien contient-il la valeur que vous recherchez?
Ensuite, vous pouvez utiliser une expression XPath qui sélectionne l'élément a
deuxième mais dernier et à partir de là son élément span
enfant.
//div[@class="pager"] <- select each <div> where the attribute class equals "pager"
//div[@class="pager"]/a <- select each <a> that is a direct child of the pager div
//div[@class="pager"]/a[position()=last()-1] <- select the <a> that is second but last
//div[@class="pager"]/a[position()=last()-1]/span <- select the direct child <span> of that second but last <a> element in the pager <div>
(vous voudrez peut-être chercher un bon tutoriel XPath ;-))
$doc->loadhtml($html);
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query('//div[@class="pager"]/a[position()=last()-1]/span');
if (0 < $nodelist->length) {
echo $nodelist->item(0)->nodeValue;
}
else {
echo 'not found';
}
génial - merci, je me réjouis de ce –
Salut j'ai essayé cela, mais il est revenu getUsers fonction zéro (userurl de $) { $ doc = new DOMDocument; $ doc-> loadhtml ($ userurl); $ xpath = new DOMXPath ($ doc); $ nodelist = $ xpath-> query ('// span [@ class = "page-nombres"]'); print_r ($ nodelist); echo 'il y a', $ nodelist-> longueur, 'span éléments ayant class = "page-numbers"'; } L'URL est http://ask.recipelabs.com/users –
Si vous transmettez l'URL, vous avez besoin de loadhtmlFILE(), pas de loadhtml(). – VolkerK