开发者

DOMElement cloning and appending: 'Wrong Document Error'

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 'DOM开发者_C百科Exception' 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.


You'll have to append the result of the importNode method to the DOM. Keep in mind that the method could return false when it cannot be imported

if ($importedNode = $doc2->importNode($root->cloneNode())) {
    $root2->appendChild($importedNode);
}

If you need to import the node, all of it's child nodes (resursively) and/or the node's attributes use the optional second parameter deep:

if ($importedNode = $doc2->importNode($root->cloneNode(), true)) {
    $root2->appendChild($importedNode);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜