SimpleXML is a PHP extension that allows you to parse and manipulate XML data. When you save an XML document using SimpleXML's asXML() function, all the data is output in a single line, which can be problematic when you want to preserve line breaks.
To preserve line breaks in your XML document, you can use the DOMDocument class. Here's how:
$xml = new SimpleXMLElement('<data><name>blah</name><class>blah</class><area>blah</area></data>'); $dom = new DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadXML($xml->asXML()); echo $dom->saveXML();
The DOMDocument class provides more control over the formatting of your XML document. By setting the preserveWhiteSpace and formatOutput properties, you can retain line breaks and improve the readability of your XML. The saveXML() function then outputs the XML document with the desired formatting.
The above is the detailed content of How to Preserve Line Breaks When Saving XML with PHP SimpleXML?. For more information, please follow other related articles on the PHP Chinese website!