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

时间:2009-04-28 17:11:12

标签: php formatting simplexml

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

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

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

我该如何做到这一点?

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

我正在使用asXML()功能。

感谢。

4 个答案:

答案 0 :(得分:140)

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

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

答案 1 :(得分: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');

答案 2 :(得分:17)

使用dom_import_simplexml转换为DomElement。然后使用其容量格式化输出。

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

答案 3 :(得分:2)

GumboWitman回答;使用DOMDocument::loadDOMDocument::save从现有文件(我们这里有很多新手)加载和保存XML文档。

<?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);
}
?>