PHP simpleXML how to save the file in a formatted way? PHP simpleXML how to save the file in a formatted way? php php

PHP simpleXML how to save the file in a formatted way?


You could use the DOMDocument class to reformat your code:

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


Gumbo's solution does the trick. You can do work with simpleXml above and then add this at the end to echo and/or save it with formatting.

Code below echos it and saves it to a file (see comments in code and remove whatever you don't want):

//Format XML to save indented tree rather than one line$dom = new DOMDocument('1.0');$dom->preserveWhiteSpace = false;$dom->formatOutput = true;$dom->loadXML($simpleXml->asXML());//Echo XML - remove this and following line if echo not desiredecho $dom->saveXML();//Save XML to file - remove this and following line if save not desired$dom->save('fileName.xml');


Use dom_import_simplexml to convert to a DomElement. Then use its capacity to format output.

$dom = dom_import_simplexml($simple_xml)->ownerDocument;$dom->preserveWhiteSpace = false;$dom->formatOutput = true;echo $dom->saveXML();