PHP to get all img src="" in a block of html?

In my php script I’m pulling a few blocks of html from a database. Inside that html is all the normal html goodness you would expect. <h1’s><table’s> and of course <img’s>

I need to be able to suck all of the src tags in <img src="http://www.someimagehere.com/img.jpg /> and put them in a php array.

I’ve never really tried anything like this in php so I’m open to any guidance, suggestions or ideas you may have to make this work. I guess I’m not even sure where to begin…?

Thanks in advance for any guidance you may be able to provide.

*side note: This operation needs to be performed so I can use phpmailer to email the html and rather than <img src=“http://www…” /> I have to change it to <img src=“cid:someimage” /> and I want the script to do this dynamically. I say this b/c there may be an easier way to skin this cat. Again, I’m open to ideas.

Thanks!

rusty

This’ll do it for you. :slight_smile:


$html = '
<html>
    <head>
        <title>img src example</title>
    </head>
    <body>
        <img src="http://www.example.com/imageOne.jpg" />
        <img src="http://www.example.com/imageTwo.jpg" />
    </body>
</html>
';

$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
foreach($xpath->query("//img/@src") as $src){
    echo $src->nodeValue;
}
/*
    http://www.example.com/imageOne.jpg
    http://www.example.com/imageTwo.jpg
*/