PHP XML: How to Output a Well-Formatted Structure
When generating XML documents using PHP, it's desirable to produce a structured and readable output. However, by default, PHP's XML processing libraries may not provide the desired formatting. This article provides a solution to output well-formatted XML, including indentation and UTF-8 encoding.
Consider the following code snippet:
$doc = new DomDocument('1.0'); // ... $xml_string = $doc->saveXML(); echo $xml_string;
Executing this code may result in a poorly formatted XML string, with elements appearing on a single line:
<xml><child>ee</child></xml>
To improve the formatting and indentation, adjust the XML document's properties as follows:
$doc->preserveWhiteSpace = false; $doc->formatOutput = true; $xml_string = $doc->saveXML();
This will produce a well-indented XML structure:
<?xml version="1.0"?> <root> <error> <a>eee</a> <b>sd</b> <c>df</c> </error> <!-- ... --> </root>
Additionally, to ensure UTF-8 encoding, you can specify the encoding during the initialization of the DOMDocument:
$doc = new DomDocument('1.0', 'UTF-8');
By following these steps, you can generate well-formatted and UTF-8 encoded XML documents using PHP's XML processing capabilities.
The above is the detailed content of How Can I Generate Well-Formatted XML with PHP?. For more information, please follow other related articles on the PHP Chinese website!