PHP DOM 在没有 DOMDocumentFragment::appendXML 的情况下将 HTML 附加到现有文档

标签 php domdocument tidy

我需要将一些任意 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/

相关文章:

r - 打印同表中的关系和相关性的显着性

php - 使用 DomDocument 添加条件注释

php - 使用 DOMXpath::query 获取 id 旁边的第一张图片

php - 从外部网站获取 DIV 内容

c++ - 如何将 libtidy 的解析输出转换为 char *

php - 缩进文档,忽略问题

php - 警告 : mysql_connect(): Access denied for user 'root' @'localhost' (using password: YES)

javascript - 如何在我的应用程序中正确处理闰秒

PHP代理下载文件

php - 无法使用PHP函数ssh2_tunnel创建SSH隧道