Get img src with PHP

Use a HTML parser like DOMDocument and then evaluate the value you’re looking for with DOMXpath:

$html="<img id="12" border="0" src="https://stackoverflow.com/images/image.jpg"
         alt="Image" width="100" height="100" />";

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "https://stackoverflow.com/images/image.jpg"

Or for those who really need to save space:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");

And for the one-liners out there:

$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));

Leave a Comment

tech