Home > Backend Development > PHP Tutorial > How Can I Format XML Output with Line Breaks When Using SimpleXML in PHP?

How Can I Format XML Output with Line Breaks When Using SimpleXML in PHP?

Barbara Streisand
Release: 2024-12-01 16:05:18
Original
954 people have browsed it

How Can I Format XML Output with Line Breaks When Using SimpleXML in PHP?

Formatting XML Output in PHP Using SimpleXML

When adding data to an existing XML file with PHP's SimpleXML, it often appears as a single continuous line, like:

<name>blah</name><class>blah</class><area>blah</area> ...
Copy after login

However, for readability and clarity, it's desirable to introduce line breaks to format the output, like:

<name>blah</name>
<class>blah</class>
<area>blah</area>
Copy after login

One way to achieve this is through the DOMDocument class:

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
Copy after login

By setting preserveWhiteSpace to false, unnecessary whitespace is removed, and by setting formatOutput to true, line breaks and indents are introduced. This will output the formatted XML.

The above is the detailed content of How Can I Format XML Output with Line Breaks When Using SimpleXML 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