Home >Backend Development >PHP Tutorial >How Can I Format XML Output with Line Breaks When Using SimpleXML in PHP?
Formatting XML Output in PHP Using SimpleXML
When adding data to an existing XML file with PHP's SimpleXML, it often appears as a single continuous line, like:
<name>blah</name><class>blah</class><area>blah</area> ...
However, for readability and clarity, it's desirable to introduce line breaks to format the output, like:
<name>blah</name> <class>blah</class> <area>blah</area>
One way to achieve this is through the DOMDocument class:
$dom = new DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadXML($simpleXml->asXML()); echo $dom->saveXML();
By setting preserveWhiteSpace to false, unnecessary whitespace is removed, and by setting formatOutput to true, line breaks and indents are introduced. This will output the formatted XML.
The above is the detailed content of How Can I Format XML Output with Line Breaks When Using SimpleXML in PHP?. For more information, please follow other related articles on the PHP Chinese website!