91

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

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

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

我怎样才能做到这一点?

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

我正在使用asXML()功能。

谢谢。

4

4 回答 4

151

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

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
于 2009-04-28T17:16:27.870 回答
32

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-11-24T22:01:18.260 回答
19

用于dom_import_simplexml转换为 DomElement。然后使用它的容量来格式化输出。

$dom = dom_import_simplexml($simple_xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
于 2009-04-28T20:56:29.087 回答
2

正如秋葵威特曼回答的那样;使用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);
}
?>
于 2011-06-07T00:21:02.127 回答