In PHP XML programming, formatting output as desired can be a concern. When an XML document is rendered in a browser, it may appear as a single line, without the desired structure and indentation. This issue arises when white space is stripped during the XML saving process.
Solution:
To resolve this, PHP provides two parameters for DomDocument:
Implementation:
// ... (code as before) // Set the formatting parameters $doc->preserveWhiteSpace = false; $doc->formatOutput = true; // Get the formatted XML output $xml_string = $doc->saveXML(); echo $xml_string;
Alternatively, these parameters can be set immediately after creating the DomDocument:
$doc = new DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true;
Sample Output:
<?xml version="1.0"?> <root> <error> <a>eee</a> <b>sd</b> <c>df</c> </error> <error> <a>eee</a> <b>sd</b> <c>df</c> </error> <error> <a>eee</a> <b>sd</b> <c>df</c> </error> </root>
Indentation:
PHP does not allow altering the indentation character. However, you can post-process the XML using regular expressions or utilize the tidy extension's tidy_repair_string function, which provides indentation options.
The above is the detailed content of How Can I Properly Format XML Output in PHP?. For more information, please follow other related articles on the PHP Chinese website!