SimpleXML::addChild() can't add line break when output to a xml
<?xml version="1.0" encoding="utf-8"?><items>
<item><title>title3</title><desc>This is some desc开发者_如何学JAVA3</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>
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.
精彩评论