Home >Backend Development >PHP Tutorial >How Can I Output Well-Formatted and UTF-8 Encoded XML in PHP?

How Can I Output Well-Formatted and UTF-8 Encoded XML in PHP?

DDD
DDDOriginal
2024-11-24 04:20:14202browse

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

  • By setting preserveWhiteSpace to false, you remove unnecessary white space from the XML document.
  • Setting formatOutput to true instructs the saveXML method to format the output XML according to indentation rules.
  • The UTF-8 argument in the new DomDocument constructor sets the encoding to UTF-8.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn