'Set SimpleXMLElement's value by other SimpleXMLElement's value, preserving potential CDATA

I am trying to merge values from two different XML's together, setting one node's value by another node.

$file1=simplexml_load_string('<grp><nde></nde></grp>');
$file2=simplexml_load_string('<grp><nde><![CDATA[ja]]></nde></grp>');

$file1->xpath('//grp')[0]->nde = $file2->xpath('//grp')[0]->nde;

echo $file1->asXml();

outputs

<?xml version="1.0"?>
<grp>
  <nde>ja</nde>
</grp>

should output

<?xml version="1.0"?>
<grp>
  <nde><![CDATA[ja]]></nde>
</grp>

How to set the value properly preserving the CDATA?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source