PHP SimpleXML new line

I created an XML file using simple PHP-XML, saved the file. When opening a file in php using fopen and printing the contents. my XML is as follows: (see below)

<?xml version="1.0" encoding="UTF-8"?> <home><orderList><delivery_cost>0.00</delivery_cost><delivery_surname>TEST</delivery_surname><delivery_postcode>1234</delivery_postcode><status>1</status></orderList></home> 

I want the xml file to look all indented and new lines for each element. Does anyone know how to do this?

thanks

+6
php pretty-print simplexml
source share
3 answers

You can do this using the formatOutput property of the DOMDocument .

Save the XML this way, instead, assume that your XML is in a variable called $yourXML , and you want to save it to a file in $xmlFilePath :

 $dom = new DOMDocument(); $dom->loadXML($yourXML); $dom->formatOutput = true; $formattedXML = $dom->saveXML(); $fp = fopen($xmlFilePath,'w+'); fwrite($fp, $formattedXML); fclose($fp); 

Code adapted from here .

+11
source share

This is called "pretty printed," and SimpleXML does not. If you do a search in Qaru and elsewhere on the Internet, you will find special solutions that do this.

Pretty printing is good for visualization, but I do not recommend saving documents in this format .

If you are still looking for a pretty printer, you can try SimpleDOM asPrettyXML ()

 include 'SimpleDOM.php'; $home = simpledom_load_string('<?xml version="1.0" encoding="UTF-8"?> <home><orderList><delivery_cost>0.00</delivery_cost><delivery_surname>TEST</delivery_surname><delivery_postcode>1234</delivery_postcode><status>1</status></orderList></home>'); echo $home->asPrettyXML(); 
+2
source share

echo "\ n"; for a new line in xml

ob_start (); echo "." \ N ";?>

-3
source share

All Articles