如何以格式化的方式保存文件?

我正在尝试使用 PHP 的 SimpleXML 向现有的 XML 文件添加一些数据。问题在于,它将所有数据都添加到一行中:

<name>blah</name><class>blah</class><area>blah</area> ...

以此类推。都在一条线上。如何引入换行符?

我要怎么弄成这样?

<name>blah</name>
<class>blah</class>
<area>blah</area>

我正在使用 asXML()函数。

谢谢。

60498 次浏览

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();

Use dom_import_simplexml to convert to a DomElement. Then use its capacity to format output.

$dom = dom_import_simplexml($simple_xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();

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');

As Gumbo and Witman answered; loading and saving an XML document from an existing file (we're a lot of newbies around here) with DOMDocument::load and DOMDocument::save.

<?php
$xmlFile = 'filename.xml';
if( !file_exists($xmlFile) ) die('Missing file: ' . $xmlFile);
else
{
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dl = @$dom->load($xmlFile); // remove error control operator (@) to print any error message generated while loading.
if ( !$dl ) die('Error while parsing the document: ' . $xmlFile);
echo $dom->save($xmlFile);
}
?>