PHP SimpleXML new line
Asked Answered
H

3

11

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

Hydrous answered 3/12, 2009 at 14:21 Comment(1)
how are you saving the XML file?Jere
D
15

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.

Dichy answered 3/12, 2009 at 14:28 Comment(2)
You can also import the dom representation from your SimpleXML object to a DOMElement/DOMDocument object and than set the formatOutput property on the DOMDocument object. This way you don't have to re-parse the xml string. see <docs.php.net/function.dom-import-simplexml> and <docs.php.net/class.domnode#domnode.props.ownerdocument>Mcdade
The problem with formatOutput is it will only work if you don't have any text nodes. IOW, if there's even one linebreak between two nodes, it will not try to prettify the output.Recurvate
R
4

This is called "pretty printing" and SimpleXML does not do that. If you search on Stack Overflow and elsewhere on the web you'll find custom solutions that do that.

Pretty printing is good for visulation but I don't recommend saving documents in that format.

If you're still looking for a pretty-printer, you can try SimpleDOM's 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();
Recurvate answered 3/12, 2009 at 14:33 Comment(0)
M
-4

echo "\n"; for new line in xml

ob_start(); echo ' ' . "\n";?>

Marcum answered 22/9, 2016 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.