我尝试使用PHP的SimpleXML向现有的XML文件添加一些数据,但问题是它把所有数据都添加到了同一行:
<name>blah</name><class>blah</class><area>blah</area> ...
等等。所有内容都在一行中。如何插入换行符?
我该如何使它变成这样?
<name>blah</name>
<class>blah</class>
<area>blah</area>
我正在使用asXML()
函数。
谢谢。
我尝试使用PHP的SimpleXML向现有的XML文件添加一些数据,但问题是它把所有数据都添加到了同一行:
<name>blah</name><class>blah</class><area>blah</area> ...
等等。所有内容都在一行中。如何插入换行符?
我该如何使它变成这样?
<name>blah</name>
<class>blah</class>
<area>blah</area>
我正在使用asXML()
函数。
谢谢。
您可以使用DOMDocument类来重新格式化您的代码:
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
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');
dom_import_simplexml
将其转换为DomElement。然后使用其能力来格式化输出。$dom = dom_import_simplexml($simple_xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
documentElement
应该是 ownerDocument
。不确定 API 是否已更改或这只是一个打字错误。我已经纠正了它。 - troelskn正如Gumbo和Witman所回答的一样,使用DOMDocument::load和DOMDocument::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);
}
?>