How Can I Properly Format XML Output from PHP?

Susan Sarandon
Release: 2024-11-25 02:01:18
Original
621 people have browsed it

How Can I Properly Format XML Output from PHP?

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

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

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

For additional customization, we can use regular expressions to replace spaces with tabs:

$xml_string = preg_replace('/(?:^|\G)  /um', "\t", $xml_string);
Copy after login

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

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!

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