Indentation with DOMDocument in PHP

Josh Leitzel picture Josh Leitzel · Apr 14, 2009 · Viewed 21.9k times · Source

I'm using DOMDocument to generate a new XML file and I would like for the output of the file to be indented nicely so that it's easy to follow for a human reader.

For example, when DOMDocument outputs this data:

<?xml version="1.0"?>
<this attr="that"><foo>lkjalksjdlakjdlkasd</foo><foo>lkjlkasjlkajklajslk</foo></this>

I want the XML file to be:

<?xml version="1.0"?>
<this attr="that">
    <foo>lkjalksjdlakjdlkasd</foo>
    <foo>lkjlkasjlkajklajslk</foo>
</this>

I've been searching around looking for answers, and everything that I've found seems to say to try to control the white space this way:

$foo = new DOMDocument();
$foo->preserveWhiteSpace = false;
$foo->formatOutput = true;

But this does not seem to do anything. Perhaps this only works when reading XML? Keep in mind I'm trying to write new documents.

Is there anything built-in to DOMDocument to do this? Or a function that can accomplish this easily?

Answer

Angel picture Angel · Jan 25, 2013

DomDocument will do the trick, I personally spent couple of hours Googling and trying to figure this out and I noted that if you use

$xmlDoc = new DOMDocument ();
$xmlDoc->loadXML ( $xml );
$xmlDoc->preserveWhiteSpace = false;
$xmlDoc->formatOutput = true;
$xmlDoc->save($xml_file);

In that order, It just doesn't work but, if you use the same code but in this order:

$xmlDoc = new DOMDocument ();
$xmlDoc->preserveWhiteSpace = false;
$xmlDoc->formatOutput = true;
$xmlDoc->loadXML ( $xml );
$xmlDoc->save($archivoxml);

Works like a charm, hope this helps