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;
Alternatively, these parameters can be set immediately after creating the DomDocument:
$doc = new DomDocument('1.0'); $doc->preserveWhiteSpace = false; $doc->formatOutput = true;
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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
