Formatting XML Output with SimpleXML
When adding data to an XML file using PHP's SimpleXML, it's possible to encounter the issue of all data being appended in a single line. This can make the XML output unreadable and difficult to parse.
To introduce line breaks and improve the readability of the XML output, one can leverage the DOMDocument class. This class provides methods for reformatting the XML code:
$dom = new DOMDocument('1.0'); // Create DOMDocument object $dom->preserveWhiteSpace = false; // Remove whitespace $dom->formatOutput = true; // Set formatting $dom->loadXML($simpleXml->asXML()); // Load XML from SimpleXML object echo $dom->saveXML(); // Output formatted XML
This code snippet creates a DOMDocument object, sets options to remove whitespace and enable formatting, loads the XML generated by SimpleXML's asXML() function into the object, and finally prints the formatted XML representation.
The above is the detailed content of How Can I Format XML Output Generated by PHP\'s SimpleXML?. For more information, please follow other related articles on the PHP Chinese website!