[英]convert string to domelement in php
Is there any way to convert string to a DOMElement in php (not a DOMDocument) such that I can import it into a DOMDocumment? 有没有办法将字符串转换为php(不是DOMDocument)中的DOMElement,以便我可以将其导入DOMDocumment? For example have the HTML string:
例如,有HTML字符串:
<div><div>Add Example</div><div>View more examples</div></div>
I would like to have it as though I used DOMDocument::createElement to create it. 我想让它好像我使用DOMDocument :: createElement来创建它。 Then I would like to append it to a child of a DOMDocumment.
然后我想将它附加到DOMDocumment的子项。
Unless you want to write your own HTML parser you will need to use a DOMDocument to create DOMElements. 除非您想编写自己的HTML解析器,否则您需要使用DOMDocument来创建DOMElements。
class MyApp {
static function createElementFromHTML($doc,$str) {
$d = new DOMDocument();
$d->loadHTML($str);
return $doc->importNode($d->documentElement,true);
}
}
The problem with this method is shown in the following string 此方法的问题显示在以下字符串中
$str = "<div>1</div><div>2</div>";
This obviously doesn't have a single parent. 这显然没有单亲。 Instead you should be ready to handle an array of DOMNode's
相反,你应该准备好处理一组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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.