When utilizing PHP's SimpleXML library to manipulate XML files, it's often encountered that the asXML() function saves data as a single, compact line. To address this and introduce line breaks for readability, consider the following approach:
As an alternative to SimpleXML, the DOMDocument class provides options to reformat and beautify XML content. Here's a code snippet that demonstrates this:
$simpleXml = // Your existing SimpleXML object $dom = new DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadXML($simpleXml->asXML()); echo $dom->saveXML();
By setting preserveWhiteSpace to false and formatOutput to true, the DOMDocument will automatically reformat your XML content, adding line breaks and indentation. This will produce a more structured and readable XML document.
If desired, you can further customize the formatting by adjusting the indentation settings within the DOMDocument object. For instance, to use two spaces for indentation, use the following code:
$dom->formatOutput = true; $dom->loadXML($simpleXml->asXML()); $dom->saveXML(null, LIBXML_NOEMPTYTAG);
This will result in an XML document formatted with two-space indentation.
The above is the detailed content of How Can I Format XML Output from PHP\'s SimpleXML to Improve Readability?. For more information, please follow other related articles on the PHP Chinese website!