有什么方法可以将字符串转换为php中的DOMElement(而不是DOMDocument),以便可以将其导入DOMDocumment?例如,具有HTML字符串:
<div><div>Add Example</div><div>View more examples</div></div>
Run Code Online (Sandbox Code Playgroud)
我想像使用DOMDocument :: createElement来创建它一样。然后,我想将其附加到DOMDocumment的子级中。
除非您想编写自己的HTML解析器,否则将需要使用DOMDocument来创建DOMElement。
class MyApp {
static function createElementFromHTML($doc,$str) {
$d = new DOMDocument();
$d->loadHTML($str);
return $doc->importNode($d->documentElement,true);
}
}
Run Code Online (Sandbox Code Playgroud)
以下字符串显示了此方法的问题
$str = "<div>1</div><div>2</div>";
Run Code Online (Sandbox Code Playgroud)
这显然没有单亲。相反,您应该准备处理DOMNode的数组
class MyApp {
static function createNodesFromHTML($doc,$str) {
$nodes = array();
$d = new DOMDocument();
$d->loadHTML("<html>{$str}</html>");
$child = $d->documentElement->firstChild;
while($child) {
$nodes[] = $doc->importNode($child,true);
$child = $child->nextSibling;
}
return $nodes;
}
}
Run Code Online (Sandbox Code Playgroud)