作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我需要将一些任意 HTML 加载到现有的 DOMDocument
树中。以前的答案建议使用 DOMDocumentFragment
及其 appendXML
处理这个问题的方法。
作为@Owlvark在评论中指出,xml 不是 html,因此这不是一个好的解决方案。
我遇到的主要问题是 &ndash
之类的实体导致错误,因为 appendXML
方法需要格式正确的 XML。
我们可以定义实体,但这并没有解决并非所有 html 都是有效 xml 的问题。
将 HTML 导入 DOMDocument
树的好的解决方案是什么?
最佳答案
我想出的解决方案是按照@FrankFarmer 的建议使用DomDocument::loadHtml
,然后获取已解析的节点并将它们导入到我当前的文档中。我的实现看起来像这样
/**
* Parses HTML into DOMElements
* @param string $html the raw html to transform
* @param \DOMDocument $doc the document to import the nodes into
* @return array an array of DOMElements on success or an empty array on failure
*/
protected function htmlToDOM($html, $doc) {
$html = '<div id="html-to-dom-input-wrapper">' . $html . '</div>';
$hdoc = DOMDocument::loadHTML($html);
$child_array = array();
try {
$children = $hdoc->getElementById('html-to-dom-input-wrapper')->childNodes;
foreach($children as $child) {
$child = $doc->importNode($child, true);
array_push($child_array, $child);
}
} catch (Exception $ex) {
error_log($ex->getMessage(), 0);
}
return $child_array;
}
关于PHP DOM 在没有 DOMDocumentFragment::appendXML 的情况下将 HTML 附加到现有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12376686/
我正在从我的数据库中检索一些 html 字符串,我想将这些字符串解析到我的 DOMDocument 中。问题是,DOMDocument 在特殊字符处发出警告。 Warning: DOMDocument
我需要将一些任意 HTML 加载到现有的 DOMDocument 树中。以前的答案建议使用 DOMDocumentFragment及其 appendXML处理这个问题的方法。 作为@Owlvark在评
我是一名优秀的程序员,十分优秀!