简体   繁体   English

php,如何克隆DOMElement?

[英]php, how to clone DOMElement?

Official documentation says that DOMElement has inherited method cloneNode http://php.net/manual/en/class.domelement.php .官方文档说 DOMElement 继承了方法 cloneNode http://php.net/manual/en/class.domelement.php If i try to clone, it does not work.如果我尝试克隆,它不起作用。 How to copy element from one DOMDocument to another?如何将元素从一个 DOMDocument 复制到另一个? Namely, i have misplaced head, thus i have somehow to copy head and body, and than to echo them in right order.也就是说,我的头部放错了位置,因此我必须以某种方式复制头部和身体,而不是以正确的顺序呼应它们。

ob_start();
$viewData = $this->data; 
include_once( $this->viewTemplPath.$this->file );
$buffer = ob_get_clean();
$doc = new \DOMDocument();
$doc->loadHTML($buffer);

$head = $doc->getElementsByTagName('head')->item(0);
print_r('<br><br> 184 view.php head='); var_dump($head); 

$body = $doc->getElementsByTagName('body')->item(0);
print_r('<br><br> 188 view.php body='); var_dump($body); 

$docNew = new \DOMDocument();
$headNew = $head->cloneNone(true); // Fatal error: Call to undefined method DOMElement::cloneNone()
$docNew->appendChild($headNew);
$bodyNew = $body->cloneNone(true); // Fatal error: Call to undefined method DOMElement::cloneNone()
$docNew->appendChild($bodyNew);

echo $docNew->saveHTML();  

In order to clone the Element, the solution is to import the Element i want to clone to the Document, and than add it as a child : http://php.net/manual/en/domdocument.importnode.php This does not through errors, and echoes the new document. 为了克隆Element,解决方案是将要克隆的Element导入到Document中,然后将其添加为子元素: http : //php.net/manual/zh/domdocument.importnode.php通过错误,并回显新文档。 But this does not resolve the problem with misplaced head. 但这不能解决头部放错的问题。

ob_start();
$viewData = $this->data; 
include_once( $this->viewTemplPath.$this->file );
$buffer = ob_get_clean();
$doc = new \DOMDocument();
$doc->loadHTML($buffer);
$head = $doc->getElementsByTagName('head')->item(0);
$body = $doc->getElementsByTagName('body')->item(0);

$docNew = new \DOMDocument();
$headNew = $docNew->importNode($head, true); 
$docNew->appendChild($headNew);
$bodyNew = $docNew->importNode($body, true); 
$docNew->appendChild($bodyNew);

echo $docNew->saveHTML(); 

你有错别字,你写的CloneNone(true) ,它应该是cloneNode(true)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM