Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SimpleXML new line

I have created a XML file using PHP's simple XML, saved the file. When opening the file in php using fopen and printing the contents. my XML looks like this: (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 looking all indented and on new lines for each element. Does anybody know how to do this?

Thanks

like image 967
phpNutt Avatar asked Dec 03 '09 14:12

phpNutt


People also ask

What is SimpleXML extension?

SimpleXML is a PHP extension that allows users to easily manipulate/use XML data. It was introduced in PHP 5 as an object oriented approach to the XML DOM providing an object that can be processed with normal property selectors and array iterators.

HOW include XML file in PHP?

$dom2 = new DOMDocument; $dom2->load('existingFile. xml'); $dom2->documentElement->appendChild($dom2->importNode($fragment, true)); This would append the fragment as the last child of the root node.


1 Answers

You can do this using the formatOutput property of DOMDocument.

Save your XML like this instead, presuming your XML is in a variable called $yourXML, and you want to save it to a file at $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.

like image 157
Dominic Rodger Avatar answered Sep 28 '22 04:09

Dominic Rodger