Can I request the first 5 images using a DOMDocument?

Can I request the first 5 images using a DOMDocument?

$dom = new DOMDocument; $list = $dom->query('img'); 
+4
source share
2 answers

With XPath you can get all the images as follows:

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

Then you limit the results to only repetition for the first five.

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

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

+7
source

You can use getElementsByTagName to build and array images:

 $dom = new DOMDocument(); $dom->loadHTML($string); $images = $dom->getElementsByTagName('img'); $result = array(); for ($i=0; $i<5; $i++){ $node = $images->item($i); if (is_object( $node)){ $result[] = $node->ownerDocument->saveXML($node); } } 
+1
source

Source: https://habr.com/ru/post/1491372/


All Articles