DOMDocument get element attribute


DOMDocument get element attribute

我使用DOMDocument对象从中获取一些数据:

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

使用此代码:

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);

我得到了整个div容器,但我只想获取图像src属性。

它对我有用:

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

收益 率:

string 'some_image_src' (length=14)