tags:

views:

35

answers:

3

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!

+1  A: 

Look at PHP's XMLWriter.

Noel M
+1  A: 

//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> 
JapanPro
Btw, XMLWriter is better than the DOM functions? Looks nicer though.
fabrik
+1  A: 

With DOM you can do

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

gives

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

See DOMDocument::formatOutput property description.

Gordon