Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleXML::addChild() can't add line break when output to a xml

Tags:

php

simplexml

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

There is no line break between each node element when using asXML() to output?

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

<?xml version="1.0" encoding="utf-8"?>
<items>
<item>
<title>title3</title>
<desc>This is some desc3</desc>
</item>
</items>
like image 699
mko Avatar asked Sep 26 '10 09:09

mko


1 Answers

The SimpleXML extension is limited to format the output, it's sister extension, DOMDocument has support for output formatting. The XML string from your example and making use of DOMDocument::$preserveWhiteSpace and DOMDocument::$formatOutput to control the formatttings:

$doc = new DOMDocument();

$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

$doc->loadXML($string);

echo $doc->saveXML();

This will output a nicely indented XML with the linebreaks where you have asked for them:

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

If you further need to manipulate the indent, you can make use of regular expressions which has been outlined in a related question and answer: Converting indentation with preg_replace (no callback).

If you don't want to use that method you could also switch from SimpleXML to something else and then to XMLWriter which provides a method to set the indentation (XMLWriter::setIndent) of printed XML. You would need to find an interim representation of your XML model to write it with XMLWriter however which does not look that trivial.

like image 181
halfdan Avatar answered Oct 26 '22 18:10

halfdan