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
Barbara StreisandOriginal
2024-12-01 16:05:18889browse

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

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>

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();

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!

Statement:
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