The SimpleXML extension is limited to output formatting; its sister extension, DOMDocument supports output formatting. The XML string from your example and using DOMDocument::$preserveWhiteSpace and DOMDocument::$formatOutput to manage the formats:
$doc = new DOMDocument(); $doc->preserveWhiteSpace = false; $doc->formatOutput = true; $doc->loadXML($string); echo $doc->saveXML();
As a result, you will get XML with an excellent indentation, in which you ask them:
<?xml version="1.0" encoding="utf-8"?> <items> <item> <title>title3</title> <desc>This is some desc3</desc> </item> <empty/> </items>
If you still need to manipulate the indentation, you can use the regular expressions that were outlined in the corresponding question and answer: Convert indentation with preg_replace (without a callback) .
If you do not want to use this method, you can also switch from SimpleXML to another, and then to XMLWriter, which provides a method for indenting ( XMLWriter :: setIndent ) printed XML. You will need to find an intermediate representation of your XML model in order to write it using XMLWriter , however this does not seem trivial.
source share