简体   繁体   English

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

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

I'm trying add some data to an existing XML file using PHP's SimpleXML.我正在尝试使用 PHP 的 SimpleXML 将一些数据添加到现有的 XML 文件中。 The problem is it adds all the data in a single line:问题是它将所有数据添加到一行中:

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

And so on.等等。 All in a single line.全部在一行中。 How to introduce line breaks?如何引入换行符?

How do I make it like this?我如何做到这一点?

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

I am using asXML() function.我正在使用asXML()函数。

Thanks.谢谢。

You could use the DOMDocument class to reformat your code:您可以使用DOMDocument 类来重新格式化您的代码:

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

Gumbo's solution does the trick. Gumbo 的解决方案可以解决问题。 You can do work with simpleXml above and then add this at the end to echo and/or save it with formatting.您可以使用上面的 simpleXml 进行工作,然后在最后添加它以回显和/或使用格式保存它。

Code below echos it and saves it to a file (see comments in code and remove whatever you don't want):下面的代码将其回显并将其保存到文件中(请参阅代码中的注释并删除您不想要的任何内容):

//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');

Use dom_import_simplexml to convert to a DomElement.使用dom_import_simplexml转换为 DomElement。 Then use its capacity to format output.然后使用它的容量来格式化输出。

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

As Gumbo and Witman answered; GumboWitman回答; loading and saving an XML document from an existing file (we're a lot of newbies around here) with DOMDocument::load and DOMDocument::save .使用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