Home > Backend Development > PHP Tutorial > How Can I Format XML Output from PHP\'s SimpleXML to Improve Readability?

How Can I Format XML Output from PHP\'s SimpleXML to Improve Readability?

DDD
Release: 2024-12-01 20:54:14
Original
626 people have browsed it

How Can I Format XML Output from PHP's SimpleXML to Improve Readability?

PHP SimpleXML: Formatting XML File on Save

When utilizing PHP's SimpleXML library to manipulate XML files, it's often encountered that the asXML() function saves data as a single, compact line. To address this and introduce line breaks for readability, consider the following approach:

Using DOMDocument

As an alternative to SimpleXML, the DOMDocument class provides options to reformat and beautify XML content. Here's a code snippet that demonstrates this:

$simpleXml = // Your existing SimpleXML object

$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 and formatOutput to true, the DOMDocument will automatically reformat your XML content, adding line breaks and indentation. This will produce a more structured and readable XML document.

Further Modifications

If desired, you can further customize the formatting by adjusting the indentation settings within the DOMDocument object. For instance, to use two spaces for indentation, use the following code:

$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
$dom->saveXML(null, LIBXML_NOEMPTYTAG);
Copy after login

This will result in an XML document formatted with two-space indentation.

The above is the detailed content of How Can I Format XML Output from PHP\'s SimpleXML to Improve Readability?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template