PHP SimpleXML new line

2019-04-28 12:15发布

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

3条回答
再贱就再见
2楼-- · 2019-04-28 12:48

echo "\n"; for new line in xml

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

查看更多
该账号已被封号
3楼-- · 2019-04-28 12:52

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.

查看更多
成全新的幸福
4楼-- · 2019-04-28 13:12

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();
查看更多
登录 后发表回答