简体   繁体   中英

DOMDocument get element attribute

I use DOMDocument object to get some data from this:

<div class="prodImg">
<a href="#"><img src="some_image_src"/></a>
</div>

With this code:

libxml_use_internal_errors(true);
$homepage = file_get_contents('some_src');
$doc = new DomDocument;
@$doc->loadHtml($homepage);
$xpath = new DomXpath($doc);
$div = $xpath->query('//*[@class="prodImg"]')->item(0);

I get the whole div container but I want to get only the image src attribute.

It works for me:

$div = $xpath->query('//*[@class="prodImg"]')->item(0)->getElementsByTagName('img')->item(0)->getAttribute('src');
var_dump($div);

Yields:

string 'some_image_src' (length=14)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM