0

Possible Duplicate:
PHP XML how to output nice format

I have the following PHP DOM code that creates a XML document in a dynamic way:

<?php

// create doctype
$dom = new DOMDocument("1.0");
// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

for ($i=1;$i<=5;$i++)
{
// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);
// create child element
$item = $dom->createElement("item");
$root->appendChild($item);
// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);
}
// save and display tree
echo $dom->saveXML();
?>

The PHP code generates the next XML code:

<?xml version="1.0"?>
<toppings><item>pepperoni</item></toppings>
<toppings><item>pepperoni</item></toppings>
<toppings><item>pepperoni</item></toppings>
<toppings><item>pepperoni</item></toppings>
<toppings><item>pepperoni</item></toppings> 

I would like to know what to change in order for the XML look like this other way:

<?xml version="1.0"?>
<toppings>
  <item>pepperoni</item>
</toppings>
<toppings>
  <item>pepperoni</item>
</toppings>
<toppings>
  <item>pepperoni</item>
</toppings>
<toppings>
  <item>pepperoni</item>
</toppings>
<toppings>
  <item>pepperoni</item>
</toppings> 
Community
  • 1
  • 1
Haritz
  • 1,702
  • 7
  • 31
  • 50
  • Minor sidenote; especially with PHP scripts that output something, be careful of the closing '?>'. It can cause an empty line at the end of your output that can bork up other scripts. – Nathaniel Ford Apr 30 '12 at 21:45

1 Answers1

6

Try $dom->formatOutput = true.

alganet
  • 2,527
  • 13
  • 24