PHP simpleXML how to save the file in a formatted way?

PhpFormattingSimplexml

Php Problem Overview


I'm trying add some data to an existing XML file using PHP's SimpleXML. The problem is it adds all the data in a single line:

<name>blah</name><class>blah</class><area>blah</area> ...

And so on. All in a single line. How to introduce line breaks?

How do I make it like this?

<name>blah</name>
<class>blah</class>
<area>blah</area>

I am using asXML() function.

Thanks.

Php Solutions


Solution 1 - Php

You could use the DOMDocument class to reformat your code:

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();

Solution 2 - Php

Gumbo's solution does the trick. You can do work with simpleXml above and then add this at the end to echo and/or save it with formatting.

Code below echos it and saves it to a file (see comments in code and remove whatever you don't want):

//Format XML to save indented tree rather than one line
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
//Echo XML - remove this and following line if echo not desired
echo $dom->saveXML();
//Save XML to file - remove this and following line if save not desired
$dom->save('fileName.xml');

Solution 3 - Php

Use dom_import_simplexml to convert to a DomElement. Then use its capacity to format output.

$dom = dom_import_simplexml($simple_xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();

Solution 4 - Php

As Gumbo and Witman answered; loading and saving an XML document from an existing file (we're a lot of newbies around here) with DOMDocument::load and DOMDocument::save.

<?php
$xmlFile = 'filename.xml';
if( !file_exists($xmlFile) ) die('Missing file: ' . $xmlFile);
else
{
  $dom = new DOMDocument('1.0');
  $dom->preserveWhiteSpace = false;
  $dom->formatOutput = true;
  $dl = @$dom->load($xmlFile); // remove error control operator (@) to print any error message generated while loading.
  if ( !$dl ) die('Error while parsing the document: ' . $xmlFile);
  echo $dom->save($xmlFile);
}
?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser61734View Question on Stackoverflow
Solution 1 - PhpGumboView Answer on Stackoverflow
Solution 2 - PhpWitmanView Answer on Stackoverflow
Solution 3 - PhptroelsknView Answer on Stackoverflow
Solution 4 - PhpquantmeView Answer on Stackoverflow