When inserting XML DOM Elements inside existing XML DOM Elements that I loaded from an XML file using the following code, none of my new elements were formatted correctly, they just showed up on one line:
<?php 
$dom = DOMDocument::load('file.xml'); 
$dom->formatOutput = true;
$dom->saveXML();
?>
I found I could pass LIBXML_NOBLANKS to the load method and it would reformat the whole document, including my added stuff:
<?php 
$dom = DOMDocument::load('file.xml', LIBXML_NOBLANKS); 
$dom->formatOutput = true;
$dom->saveXML();
?>
Hope this helps, took me hours of trial and error to figure this out!