- dom_import_simplexml: documentation ( source)
<?php
$sample = new SimpleXMLElement('<root><parent><child1></child1></parent></root>');
$node = $sample->xpath('//parent');
$node[0]->addChild('child2');
echo f($sample);
function f(SimpleXMLElement $x) {
$doc = dom_import_simplexml($x)->ownerDocument;
$doc->formatOutput = true;
return $doc->saveXML();
}