Home » Php » PHP code to traverse through a HTML file to find all the images in there?

PHP code to traverse through a HTML file to find all the images in there?

Posted by: admin July 12, 2020 Leave a comment


I wanted a php script to fetch all the images in HTML code and list it.
Can anyone help me do this, or some Idea as to how I should proceed ?
I am new to this, so any help would be appreciated.

How to&Answers:

you can use DOMDocument, or simplehtmldom. here is a DOMDocument example:

$dom = new DOMDocument();
foreach ($dom->getElementsByTagName('img') as $img) {
    echo $img->getAttribute('src').'<br>'; // or whatever you need


Run the HTML code through one of the many HTML parser libraries and then query for the src attribute value on all the img elements.


Tried looking at DOMDocument in PHP? http://php.net/manual/en/domdocument.getelementsbytagname.php

Good example from that page:

$dom = new DomDocument();
$dom->prevservWhiteSpace = false;


$imageList = $dom->getElementsByTagName('img');
$imageCnt  = $imageList->length;

for ($idx = 0; $idx < $imageCnt; $idx++) {
    print $imageList->item($idx)->nodeValue . "\n";

Should give you the basics you need.

*Disclaimer, example is slightly modified from the comment I yanked it from but this is pretty straight forward stuff.


If you want to load it from an actual php/html file…

$dom = new DomDocument();

if ([email protected]$dom->load('img.php')) {
    echo 'url does not exist';

$imgs = $dom->getElementsByTagName('img');

for ($buffer = ''; $i = 0, $len = $imgs->length; $i < $len; $i++)
  $buffer .= 'image ' . $i . ' is: ' . $imgs->item($i)->getAttribute('src') . '<br/>';

echo $buffer;


I would suggest looking into the DOM. It should provide the functionality you are looking for.


I think one of the simplest ways you could do this would be through a regular expression. Load the HTML via the DOMDocument object as mentioned but create a expression – apparently PHP has 3 different methods to do this. I’ve also written a short post on regular expressions which may help you get a foothold on the subject. They’re extremely useful in situations such as this.