Home > Backend Development > PHP Tutorial > How Can I Generate Well-Formatted XML with PHP?

How Can I Generate Well-Formatted XML with PHP?

Mary-Kate Olsen
Release: 2024-11-23 21:26:10
Original
224 people have browsed it

How Can I Generate Well-Formatted XML with PHP?

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;
Copy after login

Executing this code may result in a poorly formatted XML string, with elements appearing on a single line:

<xml><child>ee</child></xml>
Copy after login

To improve the formatting and indentation, adjust the XML document's properties as follows:

$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

$xml_string = $doc->saveXML();
Copy after login

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>
Copy after login

Additionally, to ensure UTF-8 encoding, you can specify the encoding during the initialization of the DOMDocument:

$doc = new DomDocument('1.0', 'UTF-8');
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template