我想出的解决方案是DomDocument::loadHtml
按照@FrankFarmer 的建议使用,然后获取解析的节点并将它们导入到我当前的文档中。我的实现看起来像这样
/**
* 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;
}