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

use*_*734 85 php formatting simplexml

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

<name>blah</name><class>blah</class><area>blah</area> ...
Run Code Online (Sandbox Code Playgroud)

等等.全部在一条线上.如何引入换行符?

我怎么做到这样?

<name>blah</name>
<class>blah</class>
<area>blah</area>
Run Code Online (Sandbox Code Playgroud)

我正在使用asXML()功能.

谢谢.

Gum*_*mbo 142

您可以使用DOMDocument类重新格式化代码:

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
Run Code Online (Sandbox Code Playgroud)

  • 那么SimpleXML是不可能的? (3认同)

Wit*_*man 28

Gumbo的解决方案可以解决问题.您可以使用上面的simpleXml,然后在最后添加它以回显和/或使用格式保存它.

下面的代码回显并将其保存到文件中(请参阅代码中的注释并删除任何您不想要的内容):

//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');
Run Code Online (Sandbox Code Playgroud)


tro*_*skn 17

使用dom_import_simplexml转换为一个DOMElement.然后使用其容量格式化输出.

$dom = dom_import_simplexml($simple_xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这仍然不起作用,因为preserveWhiteSpace和formatOutput应该设置_before_导入文件有任何效果:) (3认同)