phpregexdomdocument

How to get image src by class


I have this:

<a href="/Dealer-Catalog/ManufacturerID-3">[![ADTRAN][1]][1]

how to get img src (http://www.teledynamics.com/tdresources/74c42cb2-dc7f-4548-b820-2946fbe160db.jpg)

I tried a lot of things and that was the last one:

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//class='brand-logo']/img/@src)");
echo "$src";

Solution

  • That's not proper XPath syntax. Try

    $nodes = $xpath->query("//img[@class='brand-logo']");
    $src = $nodes->item(0)->getAttribute('src');
    

    First you fetch the NODE that represents the image whose src you want, THEN you get the src attribute. Note that the ->query() call returns a DOMNodeList, not a node.