我正在尝试使用PHP的SimpleXML向现有的XML文件添加一些数据。问题是它在一行中添加了所有数据:
<name>blah</name><class>blah</class><area>blah</area> ...诸若此类。全部都在一行代码中。如何引入换行符?
我怎么才能让它变成这样呢?
<name>blah</name>
<class>blah</class>
<area>blah</area>我正在使用asXML()函数。
谢谢。
发布于 2009-04-28 17:16:28
您可以使用DOMDocument class重新格式化您的代码:
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();发布于 2009-11-25 06:01:18
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');发布于 2009-04-28 20:56:29
使用dom_import_simplexml转换为DomElement。然后使用它的容量格式化输出。
$dom = dom_import_simplexml($simple_xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();https://stackoverflow.com/questions/798967
复制相似问题