Last active
September 15, 2019 04:28
-
-
Save stemar/f2a69080eb3292a3b19a03586a356d1b to your computer and use it in GitHub Desktop.
Format an unformatted XML string or unformat a formatted XML string, also accepts SimpleXMLElement xml object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function format_xml($xml, $formatOutput=TRUE, $declaration=TRUE) { | |
| $sxe = ($xml instanceof \SimpleXMLElement) ? $xml : simplexml_load_string($xml); | |
| $domElement = dom_import_simplexml($sxe); | |
| $domDocument = $domElement->ownerDocument; | |
| $domDocument->preserveWhiteSpace = false; | |
| $domDocument->formatOutput = (bool)$formatOutput; | |
| $domDocument->loadXML($sxe->asXML(), LIBXML_NOBLANKS); // Fixes newlines omitted by DomNode::appendChild() | |
| return (bool)$declaration ? $domDocument->saveXML() : $domDocument->saveXML($domDocument->documentElement); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $xml = '<Nodes><Node id="1">Content 1</Node><Node id="2">Content 2</Node></Nodes>'; | |
| echo format_xml($xml); | |
| /* | |
| <?xml version="1.0"?> | |
| <Nodes> | |
| <Node id="1">Content 1</Node> | |
| <Node id="2">Content 2</Node> | |
| </Nodes> | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment