How to extract img src, title and alt from html using php?

I did use the DOMDocument::loadHTML() method because this method can cope with HTML-syntax and does not force the input document to be XHTML. Strictly speaking the conversion to a SimpleXMLElement is not necessary – it just makes using xpath and the xpath results more simple.

function getImgSRC( $string ) {
    $doc = new DOMDocument();
    $doc->loadHTML( $string );
    $xpath = new DOMXPath($doc);
    $src = $xpath->evaluate("string(//img/@src)");
    return $src;

This is the simple function you can use to extract src from your string.


Be the first to comment