2009-04-28 124 views
81

我想使用PHP的SimpleXML将一些数据添加到现有的XML文件。问题是它把所有的数据加在一行:PHP simpleXML如何以格式化的方式保存文件?

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

等等。所有在一条线。如何引入换行符?

我该如何做到这一点?

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

我正在使用asXML()函数。

谢谢。

+0

还有PEAR [XML_Beautifier](http://pear.php.net/package/XML_Beautifier)包。 – karim79 2009-04-28 17:22:08

回答

133

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

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

谢谢。很棒。 – Alagu 2011-06-16 09:03:47

+0

谢谢。简单而高效。 – 2013-07-03 14:34:46

+2

因此,SimpleXML是不可能的? – 2014-11-18 07:52:20

17

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

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

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

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