How to save changed SimpleXML object back to file? How to save changed SimpleXML object back to file? xml xml

How to save changed SimpleXML object back to file?


Not sure I understand the issue. The asXML() method accepts an optional filename as param that will save the current structure as XML to a file. So once you have updated your XML with the hints, just save it back to file.

// Load XML with SimpleXml from string$root = simplexml_load_string('<root><a>foo</a></root>');// Modify a node$root->a = 'bar';// Saving the whole modified XML to a new filename$root->asXml('updated.xml');// Save only the modified node$root->a->asXml('only-a.xml');


If you want to save the same, you can use dom_import_simplexml to convert to a DomElement and save:

$dom = new DOMDocument('1.0');$dom->preserveWhiteSpace = false;$dom->formatOutput = true;$dom->loadXML($simpleXml->asXML());echo $dom->saveXML();