Home >Backend Development >PHP Tutorial >How Can I Format XML Output Generated by PHP\'s SimpleXML?

How Can I Format XML Output Generated by PHP\'s SimpleXML?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 07:56:10612browse

How Can I Format XML Output Generated by PHP's SimpleXML?

Formatting XML Output with SimpleXML

When adding data to an XML file using PHP's SimpleXML, it's possible to encounter the issue of all data being appended in a single line. This can make the XML output unreadable and difficult to parse.

To introduce line breaks and improve the readability of the XML output, one can leverage the DOMDocument class. This class provides methods for reformatting the XML code:

$dom = new DOMDocument('1.0'); // Create DOMDocument object
$dom->preserveWhiteSpace = false; // Remove whitespace
$dom->formatOutput = true; // Set formatting
$dom->loadXML($simpleXml->asXML()); // Load XML from SimpleXML object
echo $dom->saveXML(); // Output formatted XML

This code snippet creates a DOMDocument object, sets options to remove whitespace and enable formatting, loads the XML generated by SimpleXML's asXML() function into the object, and finally prints the formatted XML representation.

The above is the detailed content of How Can I Format XML Output Generated by PHP\'s SimpleXML?. 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