Question

I have the following code :

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$doc = new DomDocument;
$doc->preserveWhiteSpace = false;

if ($doc->loadHtml(curl_exec($ch)))
    $anchors = $doc->getElementById('comments')->getElementsByTagName('a');
?>

which searches through a distant page all the links (< a > tag) in the comments div.

I would like for this function to return only the 50 first < a > tags, without parsing through the whole div. Is that possible ? And if yes, how ?

Thanks in advance.

Was it helpful?

Solution

Use an XPath expression:

$elements = 50;

$doc = new DOMDocument;
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);
$anchors = $xpath->query(
    sprintf('//div[@id="comments"]/a[position() <= %d]', $elements)
);

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top