When working with XML in PHP, you may encounter issues with formatting. If you're not getting the desired indentation and whitespace characters when displaying XML in the browser, this article will provide a solution to help you output nicely formatted XML data.
The following PHP code creates an XML document but produces a poorly formatted output:
$doc = new DomDocument('1.0'); // create root node $root = $doc->createElement('root'); $root = $doc->appendChild($root); $signed_values = array('a' => 'eee', 'b' => 'sd', 'c' => 'df'); // process one row at a time foreach ($signed_values as $key => $val) { // add node for each row $occ = $doc->createElement('error'); $occ = $root->appendChild($occ); // add a child node for each field foreach ($signed_values as $fieldname => $fieldvalue) { $child = $doc->createElement($fieldname); $child = $occ->appendChild($child); $value = $doc->createTextNode($fieldvalue); $value = $child->appendChild($value); } } // get completed xml document $xml_string = $doc->saveXML(); echo $xml_string;
To get nicely formatted XML output, you can set the following parameters for the DomDocument object:
$doc->preserveWhiteSpace = false; $doc->formatOutput = true;
By setting preserveWhiteSpace to false, whitespace characters are removed from the output. Setting formatOutput to true enables the indentation of XML elements.
Alternatively, you can set these parameters right after creating the DomDocument:
$doc = new DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true;
The output in both cases will provide properly formatted XML:
<?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>
If you wish to further customize the indentation, you can use a regular expression-based approach:
$xml_string = preg_replace('/(?:^|\G) /um', "\t", $xml_string);
This will replace double spaces with tabs.
The above is the detailed content of How to Pretty Print XML Output in PHP?. For more information, please follow other related articles on the PHP Chinese website!