Maintaining Indentation while creating XML with DOMDocument in PHP

by manojgumber

I had to encounter with PHP and XML while working on an assignment. I had to create an XML document using PHP DOM . The problem was that XML file which was being created was not being properly indented and output was all appended in a single line.

My output was coming as

<forum filename="forum1.xml"><name>Forum 1 Name</name><description>This is forum 1</description></forum><forum filename="forum2.xml"><name>Forum 2 Name</name><description>This is forum 2</description></forum><forum filename="forum3.xml"><name>Forum 3 Name</name><description>This is forum 3</description></forum>

I wanted output as

<forum filename="forum1.xml">
           <name>Forum 1 Name</name>
               <description>This is forum 1</description>
      <forum filename="forum2.xml">
           <name>Forum 2 Name</name>
           <description>This is forum 2</description>
      <forum filename="forum3.xml">
           <name>Forum 3 Name</name>
           <description>This is forum 3</description>

I was looking for a solution to properly indent the output XML files. By searching through PHP Dom manual, I found the following solution

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

After creating an instance of DOMDocument , call these two functions and it is done. The xml created will be properly indented. I tried it on PHP5 and it worked fine for me.