Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to query the first 5 images with DOMDocument?

Tags:

dom

php

Is it possible to query the first 5 images with DOMDocument?

$dom = new DOMDocument;
       $list = $dom->query('img');
like image 931
Varada Avatar asked Feb 15 '23 22:02

Varada


1 Answers

With XPath You can fetch all images like this:

$xpath = new DOMXPath($dom);
$list = $xpath->query('//img');

Then you limit the results by only iterating over the first five.

for ($i = 0, $n = min(5, $list->length); $i < $n; ++$i) {
    $node = $list->item(0);
}

XPath is very versatile thanks to its expression language. However, in this particular case, you may not need all that power and a simple $list = $dom->getElementsByTagName('img') would yield the same result set.

like image 94
Ja͢ck Avatar answered Feb 24 '23 08:02

Ja͢ck