繁体   English   中英

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

[英]PHP simpleXML how to save the file in a formatted way?

我正在尝试使用 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();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM