Extract img url links from HTML document

I needed to find and get a webpage’s img src url links. I wanted to do this with a script on a regular basis. The solution I found was to use PHP domdocument:

http://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php

[php]
<?php
$url="http://example.com";

$html = file_get_contents($url);

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

$tags = $doc->getElementsByTagName(‘img’);

foreach ($tags as $tag) {
echo $tag->getAttribute(‘src’);
}
?>

[/php]

After spending some time using wget, cat, grep and so on to solve my problem, this little php code made my life easier 🙂

One comment

  1. Using `DOMDocument` is definitely a much better approach than relying on `grep` or regex, especially since HTML attributes can easily appear in any order or across multiple lines. It’s clean, reliable, and handles edge cases much more gracefully for automated tasks. Thanks for sharing this straightforward snippet.

Leave a Reply

Your email address will not be published. Required fields are marked *