我有这个 html 代码:
<html>
<head>
...
</head>
<body>
<div>
<div class="foo" data-type="bar">
SOMECONTENTWITHMORETAGS
</div>
</div>
</body>
我已经可以使用这个函数获取“foo”元素(但只有它的内容):
private function get_html_from_node($node){
$html = '';
$children = $node->childNodes;
foreach ($children as $child) {
$tmp_doc = new DOMDocument();
$tmp_doc->appendChild($tmp_doc->importNode($child,true));
$html .= $tmp_doc->saveHTML();
}
return $html;
}
但我想返回 DOMElement 的所有 html 标签(包括它的属性)。我该怎么做?
最佳答案
使用可选参数 DOMDocument::saveHTML
: 这表示“仅输出此元素”。
return $node->ownerDocument->saveHTML($node);
请注意,该参数仅适用于 PHP 5.3.6。在此之前,您需要使用 DOMDocument::saveXML
反而。结果可能略有不同。另外,如果您已经有了对文档的引用,您可以这样做:
$doc->saveHTML($node);
关于php - 如何获取 DOMElement 节点的 html 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12909787/