php 使用 DOMDocument::loadHTML 和 getElementsByTagName 通过标签名称获取 DOM 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11571240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:47:52  来源:igfitidea点击:

Get DOM elements by tag name with DOMDocument::loadHTML and getElementsByTagName

phpxpathdomdocument

提问by Naoise Golden

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.

对不起,如果这是重新发布的,但我无法解决它,我已经尝试了所有可用的文档和我能找到的示例。

I am trying to get the first imgelement of a string containing HTML

我正在尝试获取img包含 HTML 的字符串的第一个元素

PHP

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

This spits object(DOMNodeList)#57 (0) { }when it should find the one occurrence.

object(DOMNodeList)#57 (0) { }当它应该找到一个事件时,这会吐。

I've tried with XPath with no luck either.

我试过 XPath 也没有运气。

回答by nickb

Use this:

用这个:

$img = $dom->getElementsByTagName('img')->item(0);
echo $img->attributes->getNamedItem("src")->value;

回答by Uzair Zia

The correct answer has already been provided by @nickbbut you can also do the same without having to use getNamedItem()in the second line of the code provided by @nickb, like this:

@nickb已经提供了正确答案,但您也可以这样做,而无需getNamedItem()@nickb提供的代码的第二行中使用,如下所示:

echo $img->attributes->src->value;

NOTE: I wanted to add the above code as a comment to @nickb's answer, but I need a minimum of 50 reputations to do that. If anyone can write the above code line as a comment to @nickb's answer, please let me know. I will then delete my answer.

注意:我想将上述代码添加为@nickb答案的注释,但我至少需要 50 个声望才能做到这一点。如果有人可以将上述代码行写为对@nickb答案的评论,请告诉我。然后我会删除我的答案。