title: php: dom replace node by root node from another dom
body: <p>i need to update a node, from entire node from other document:</p>
  
  <p>Original XML:</p>
  
  <pre><code>&lt;a&gt;
  &lt;b&gt;Bat&lt;/b&gt;
  &lt;/a&gt;
  </code></pre>
  
  <p>Output i want:</p>
  
  <pre><code>&lt;a&gt;
  &lt;b&gt;bi&lt;/b&gt;
  &lt;/a&gt;
  </code></pre>
  
  <p>first attempt: replace by documentfragment</p>
  
  <pre><code>    $original = "&lt;a&gt;
      &lt;b&gt;Bat&lt;/b&gt;
      &lt;/a&gt;";
      $replace = "&lt;b&gt;Bi&lt;/b&gt;";
  
      $dom = new DOMDocument('1.0', 'utf-8');
      $dom-&gt;loadXML($original);
  
      $xpath = new DOMXpath($dom);
      $b = $xpath-&gt;query('//b')-&gt;item(0);
  
      $fragment = $dom-&gt;createDocumentFragment();
      $fragment-&gt;appendXML($replace);
  
      $dom-&gt;replaceChild($fragment, $b);
  
      echo $dom-&gt;saveXML();
  </code></pre>
  
  <p>ERROR:</p>
  
  <blockquote>
    <p>Fatal error: Uncaught exception 'DOMException' with message 'Not Found
    Error' in /home/zital/scripts/php/dom.php:17 Stack trace:</p>
    
    <h1>0 /home/zital/scripts/php/dom.php(17): DOMNode->replaceChild(Object(DOMDocumentFragment), Object(DOMElement))</h1>
    
    <h1>1 {main}   thrown in /home/zital/scripts/php/dom.php on line 17</h1>
  </blockquote>
  
  <p>second attempt: replace by importing node</p>
  
  <pre><code>$original = "&lt;a&gt;
          &lt;b&gt;Bat&lt;/b&gt;
  &lt;/a&gt;";
  $replace = "&lt;b&gt;Bi&lt;/b&gt;";
  
  $dom = new DOMDocument('1.0', 'utf-8');
  $dom-&gt;loadXML($original);
  
  $xpath = new DOMXpath($dom);
  $b = $xpath-&gt;query('//b')-&gt;item(0);
  
  $dom2 = new DOMDocument('1.0', 'utf-8');
  $dom2-&gt;loadXML($replace);
  
  $replace = $dom2-&gt;documentElement;
  $replace = $dom-&gt;importNode($replace, true);
  
  $dom-&gt;replaceChild($replace, $b);
  
  echo $dom-&gt;saveXML();
  </code></pre>
  
  <p>ERROR:</p>
  
  <blockquote>
    <p>Fatal error: Uncaught exception 'DOMException' with message 'Not Found
    Error' in /home/zital/scripts/php/dom.php:42 Stack trace:</p>
    
    <h1>0 /home/zital/scripts/php/dom.php(42): DOMNode->replaceChild(Object(DOMElement), Object(DOMElement))</h1>
    
    <h1>1 {main}   thrown in /home/zital/scripts/php/dom.php on line 42</h1>
  </blockquote>