Question: What is the best way to format XML within a PHP class.

```
$xml = "<element attribute=\"something\">...</element>";

$xml = '<element attribute="something">...</element>';

$xml = '<element attribute=\'something\'>...</element>';

$xml = <<<EOF
<element attribute="something">
</element>
EOF;

```

I'm pretty sure it is the last one!

Answer: 
With [DOM](http://de.php.net/manual/en/book.dom.php) you can do

```
$dom = new DOMDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML('<root><foo><bar>baz</bar></foo></root>');
$dom->formatOutput = TRUE;
echo $dom->saveXML();

```

gives ([live demo](http://codepad.org/hbS5iOQD))

```
<?xml version="1.0"?>
<root>
  <foo>
    <bar>baz</bar>
  </foo>
</root>

```

See [`DOMDocument::formatOutput`](http://de.php.net/manual/en/class.domdocument.php#domdocument.props.formatoutput) and [`DOMDocument::preserveWhiteSpace`](http://de.php.net/manual/en/class.domdocument.php#domdocument.props.preservewhitespace) properties description.
//Here is example using XMLWriter

```
$w = new XMLWriter;
$w->openMemory();
$w->setIndent(true);
  $w->startElement('foo');
    $w->startElement('bar');
      $w->writeElement("key", "value");
    $w->endElement();
  $w->endElement();
echo $w->outputMemory();

```

//out put

```
<foo> 
 <bar> 
  <key>value</key> 
 </bar> 
</foo> 

```