Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 553
volodymyr3131 Avatar asked Apr 15 '26 13:04

volodymyr3131


1 Answers

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)
like image 119
n-dru Avatar answered Apr 17 '26 04:04

n-dru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!