title3T...">

SimpleXML :: addChild () cannot add line breaks when exiting in xml

<?xml version="1.0" encoding="utf-8"?><items> <item><title>title3</title><desc>This is some desc3</desc></item></items> 

Is there a line break between each node element when using asXML () for output?

How to make the output of a file well-structured by adding a line break after each tag for opening and closing XML elements that contains child elements of an element:

 <?xml version="1.0" encoding="utf-8"?> <items> <item> <title>title3</title> <desc>This is some desc3</desc> </item> </items> 
+4
source share
1 answer

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.

+5
source

All Articles