Greetings.

I'm using PHP DOM functions to generate a XML document, but the result is always something like this:

<?xml version="1.0" encoding="iso-8859-1"?>
<foo><bar>baz</bar><quux>qux</quux></foo>

It would be really great if PHP could generate nicely formated XML code, such as (and I don't even ask for indentation):

<?xml version="1.0" encoding="iso-8859-1"?>
<foo>
<bar>baz</bar>
<quux>qux</quux>
</foo>

I've tried reading the docs, looking specially for any properties or methods that could explicitly generate a new line char, but couldn't find nothing.

Is this possible?

TIA,

    4 years later

    Yes, I know this is an old post, but it came up in the first of my google search on the same problem.

    My solution, set the formatOutput to true for the DOMDocument.

    So if you have:

    $foo = new DOMDocument;
    //$foo->add a bunch of xml stuff;
    print $foo->saveXML();

    You would want to change it to:

    $foo = new DOMDocument;
    $foo->formatOutput = true;
    //$foo->add a bunch of xml stuff;
    print $foo->saveXML();

    On another note, if you are loading xml from a file:

    $foo = new DOMDocument;
    $foo->formatOutput = true;
    $foo->load('file.xml', LIBXML_NOBLANKS); //ADD THIS!
    //$foo->add a bunch of xml stuff;
    print $foo->saveXML();

    If you don't use LIBXML_NOBLANKS then any nodes added to the inside of your loaded XML will appear on one line with no formatting!
    (took me hours to figure that out)

      Write a Reply...