How Can I Properly Format XML Output in PHP?

Linda Hamilton
Release: 2024-11-25 02:39:23
Original
857 people have browsed it

How Can I Properly Format XML Output in PHP?

PHP XML: Achieving Properly Formatted Output

In PHP XML programming, formatting output as desired can be a concern. When an XML document is rendered in a browser, it may appear as a single line, without the desired structure and indentation. This issue arises when white space is stripped during the XML saving process.

Solution:

To resolve this, PHP provides two parameters for DomDocument:

  • preserveWhiteSpace: Setting this to false prevents white space from being stripped.
  • formatOutput: Setting this to true instructs PHP to format the output XML aesthetically.

Implementation:

// ... (code as before)

// Set the formatting parameters
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

// Get the formatted XML output
$xml_string = $doc->saveXML();
echo $xml_string;
Copy after login

Alternatively, these parameters can be set immediately after creating the DomDocument:

$doc = new DomDocument('1.0');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
Copy after login

Sample Output:

<?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

Indentation:

PHP does not allow altering the indentation character. However, you can post-process the XML using regular expressions or utilize the tidy extension's tidy_repair_string function, which provides indentation options.

The above is the detailed content of How Can I Properly Format XML Output in 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