DOMElement cloning and appending: 'Wrong Document Error'

21,908

Solution 1

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

Solution 2

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);
}
Share:
21,908
Peter Bailey
Author by

Peter Bailey

Ex-programmer now tech leader. I also play bagpipes. And beer is awesome. "The programmer, who needs clarity, who must talk all day to a machine that demands declarations, hunkers down into a low-grade annoyance. It is here that the stereotype of the programmer, sitting in a dim room, growling from behind Coke cans, has its origins. The disorder of the desk, the floor; the yellow Post-It notes everywhere; the whiteboards covered with scrawl: all this is the outward manifestation of the messiness of human thought. The messiness cannot go into the program; it piles up around the programmer." -Ellen Ullman

Updated on August 19, 2020

Comments

  • Peter Bailey
    Peter Bailey over 3 years

    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?

  • Peter Bailey
    Peter Bailey over 14 years
    Perfect, Thanks. I was searching through the DOMNode and DOMElement APIs looking for something that would let me do this and (foolishly) never checked the DOMDocument methods =/
  • NobleUplift
    NobleUplift over 10 years
    Where did you add importNode? I added it to my code and I'm still getting the error.
  • Gumbo
    Gumbo over 10 years
    @NobleUplift You need to call importNode to import a node from one document to another document. After that you can append it as a child where you want.
  • NobleUplift
    NobleUplift over 10 years
    I was working on deeply nested tags so I needed to call $parent->ownerDocument->importNode($child, true) and then I was able to add it.