官方文档说DOMElement继承了方法cloneNode http://php.net/manual/en/class.domelement.php。如果我尝试克隆,它不起作用。如何将元素从一个DOMDocument复制到另一个DOMDocument?也就是说,我的头部错位,因此我以某种方式复制头部和身体,而不是以正确的顺序回应它们。
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();
答案 0 :(得分:0)
为了克隆元素,解决方案是将要克隆的元素导入到Document中,然后将其作为子元素添加:http://php.net/manual/en/domdocument.importnode.php 这不是通过错误,而是回应新文档。 但这并不能解决头部错位的问题。
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();