format xml string

With DOM you can do

$dom = new DOMDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML('<root><foo><bar>baz</bar></foo></root>');
$dom->formatOutput = TRUE;
echo $dom->saveXML();

gives (live demo)

<?xml version="1.0"?>
<root>
  <foo>
    <bar>baz</bar>
  </foo>
</root>

See DOMDocument::formatOutput and DOMDocument::preserveWhiteSpace properties description.

Leave a Comment