Home >Backend Development >PHP Tutorial >How Can I Output Well-Formatted and UTF-8 Encoded XML in PHP?
PHP XML: Outputting Well-Formatted XML
When creating XML documents in PHP, it's essential to ensure they're formatted correctly for readability and accessibility. By default, PHP may output unformatted XML, making it difficult to work with. This article addresses how to format PHP-generated XML for a more structured and user-friendly appearance.
Current Issue
You're experiencing difficulty outputting XML in a well-structured format, where elements are properly indented and line-separated. Instead, you're getting a compressed version of the XML, making it hard to read and edit. Additionally, you'd like the output to be in UTF-8 encoding.
Solution
To format your XML and change the encoding to UTF-8, follow these steps:
// Create a new DOMDocument object $doc = new DomDocument('1.0', 'UTF-8'); // Enable XML formatting $doc->preserveWhiteSpace = false; $doc->formatOutput = true; // ... (Continue with your XML processing) // Output the formatted XML document $xml_string = $doc->saveXML(); echo $xml_string;
Explanation
Customization
If you wish to customize the indentation character, you can use regular expressions to replace spaces with tabs:
$xml_string = preg_replace('/(?:^|\G) /um', "\t", $xml_string);
Alternatively, you can use the Tidy extension to pretty-print XML:
tidy_repair_string($xml_string, ['input-xml' => 1, 'indent' => 1, 'wrap' => 0]);
By following these techniques, you can output well-formatted XML in PHP, improving its readability and usability for various applications.
The above is the detailed content of How Can I Output Well-Formatted and UTF-8 Encoded XML in PHP?. For more information, please follow other related articles on the PHP Chinese website!