DOMElement克隆和附加:“错误的文档错误” [英] DOMElement cloning and appending: 'Wrong Document Error'

查看:110
本文介绍了DOMElement克隆和附加:“错误的文档错误”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一些我完全不了解PHP的DOM API的节点克隆。以下是一个快速重复我遇到的问题的示例文件。

  $ doc = new DOMDocument('1.0',' UTF-8'); 
$ root = $ doc-> createElement('root'); //这不行$ root = new DOMElement('root');
$ doc-> appendChild($ root);

$ doc2 = new DOMDocument('1.0','UTF-8');
$ root2 = $ doc2-> createElement('root2');
$ doc2-> appendChild($ root2);

//这里出现错误
$ root2-> appendChild($ root-> cloneNode());

当您运行此小代码段时抛出异常


致命错误:未捕获异常
'DOMException'与消息'错误
文档错误'


我不能从文档中抓取一个节点,将其克隆,然后将其附加到另一个文档?

解决方案

使用 DOMDocument-> importNode 将节点导入到其他文档中,然后再将其添加到DOM中。


There's something I don't fully understand about node cloning with the PHP's DOM api. Here's a sample file that quickly duplicates the issue I'm coming across.

$doc  = new DOMDocument( '1.0', 'UTF-8' );
$root = $doc->createElement( 'root' ); // This doesn't work either $root = new DOMElement( 'root' );
$doc->appendChild( $root );

$doc2  = new DOMDocument( '1.0', 'UTF-8' );
$root2 = $doc2->createElement( 'root2' );
$doc2->appendChild( $root2 );

// Here comes the error
$root2->appendChild( $root->cloneNode() );

When you run this little snippet an exception is thrown

Fatal error: Uncaught exception 'DOMException' with message 'Wrong Document Error'

Can I not grab a node from a document, clone it, and then append it to another document?

解决方案

Use DOMDocument->importNode to import the node into the other document before adding it to the DOM.

这篇关于DOMElement克隆和附加:“错误的文档错误”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆