Home > Backend Development > PHP Tutorial > How to Preserve Line Breaks When Saving XML with PHP SimpleXML?

How to Preserve Line Breaks When Saving XML with PHP SimpleXML?

Susan Sarandon
Release: 2024-12-03 10:11:10
Original
381 people have browsed it

How to Preserve Line Breaks When Saving XML with PHP SimpleXML?

How to Preserve Line Breaks in PHP SimpleXML

SimpleXML is a PHP extension that allows you to parse and manipulate XML data. When you save an XML document using SimpleXML's asXML() function, all the data is output in a single line, which can be problematic when you want to preserve line breaks.

Solution: Using the DOMDocument Class

To preserve line breaks in your XML document, you can use the DOMDocument class. Here's how:

$xml = new SimpleXMLElement('<data><name>blah</name><class>blah</class><area>blah</area></data>');
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
echo $dom->saveXML();
Copy after login

The DOMDocument class provides more control over the formatting of your XML document. By setting the preserveWhiteSpace and formatOutput properties, you can retain line breaks and improve the readability of your XML. The saveXML() function then outputs the XML document with the desired formatting.

The above is the detailed content of How to Preserve Line Breaks When Saving XML with PHP SimpleXML?. 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