PHP XML: Displaying XML in a Formatted Manner
This article addresses the issue of formatting XML output from PHP. In the provided code, printing the XML to a browser resulted in a flattened output with no indentation or line breaks. To resolve this, we can utilize PHP functions to enhance the formatting.
The first step involves setting the preserveWhiteSpace and formatOutput properties of the DomDocument instance:
$doc->preserveWhiteSpace = false; $doc->formatOutput = true;
Setting preserveWhiteSpace to false removes excessive whitespace within the XML, while formatOutput instructs PHP to format the XML according to its structure.
Alternatively, these properties can be set during DomDocument creation:
$doc = new DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true;
The formatted XML will now display with proper indentation and line breaks:
<?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>
For additional customization, we can use regular expressions to replace spaces with tabs:
$xml_string = preg_replace('/(?:^|\G) /um', "\t", $xml_string);
Finally, we can also employ the tidy extension (if available) with the tidy_repair_string function to format the XML:
tidy_repair_string($xml_string, ['input-xml'=> 1, 'indent' => 1, 'wrap' => 0]);
This method allows for precise control over indentation levels but will not produce tab indentation.
The above is the detailed content of How Can I Properly Format XML Output from PHP?. For more information, please follow other related articles on the PHP Chinese website!