使用DOMDocument :: loadHTML和getElementsByTagName通过标签名称获取DOM元素 [英] Get DOM elements by tag name with DOMDocument::loadHTML and getElementsByTagName
本文介绍了使用DOMDocument :: loadHTML和getElementsByTagName通过标签名称获取DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很抱歉,如果将其重新发布,但我无法解决,我已经尝试了所有可以找到的可用文档和示例。
Sorry if this is reposted, but I can't wrap my mind around it and I've tried all the available documentation and examples I could find.
我正在尝试获取包含HTML的字符串的第一个 img
元素
I am trying to get the first img
element of a string containing HTML
PHP
$html = '<p><img src="http://placekitten.com/200/300" alt="" width="200" height="300" /></p>';
$dom = new DOMDocument;
$dom->loadHTML($html);
$imgs = $dom->getElementsByTagName('img');
var_dump($imgs);
这会吐出 object(DOMNodeList)#57(0){}
应该找到一个出现的地方。
This spits object(DOMNodeList)#57 (0) { }
when it should find the one occurrence.
我尝试过XPath也没有运气。
I've tried with XPath with no luck either.
推荐答案
使用以下命令:
$img = $dom->getElementsByTagName('img')->item(0);
echo $img->attributes->getNamedItem("src")->value;
这篇关于使用DOMDocument :: loadHTML和getElementsByTagName通过标签名称获取DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文