Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active September 15, 2019 04:28
Show Gist options
  • Select an option

  • Save stemar/f2a69080eb3292a3b19a03586a356d1b to your computer and use it in GitHub Desktop.

Select an option

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.
<?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);
}
<?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