Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 876
user61734 Avatar asked Apr 28 '09 17:04

user61734


2 Answers

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();
like image 70
Gumbo Avatar answered Nov 15 '22 08:11

Gumbo


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');
like image 32
Witman Avatar answered Nov 15 '22 10:11

Witman