PHP simpleXML 如何以格式化的方式保存文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/798967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP simpleXML how to save the file in a formatted way?
提问by user61734
I'm trying add some data to an existing XML file using PHP's SimpleXML. The problem is it adds all the data in a single line:
我正在尝试使用 PHP 的 SimpleXML 将一些数据添加到现有的 XML 文件中。问题是它将所有数据添加到一行中:
<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.
谢谢。
回答by Gumbo
You could use the DOMDocument classto reformat your code:
您可以使用DOMDocument 类来重新格式化您的代码:
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
回答by Witman
Gumbo's solution does the trick. You can do work with simpleXml above and then add this at the end to echo and/or save it with formatting.
Gumbo 的解决方案可以解决问题。您可以使用上面的 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');
回答by troelskn
Use dom_import_simplexmlto convert to a DomElement. Then use its capacity to format output.
使用dom_import_simplexml转换为一个DOMElement。然后使用它的容量来格式化输出。
$dom = dom_import_simplexml($simple_xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
回答by quantme
As Gumboand Witmananswered; loading and saving an XML document from an existing file (we're a lot of newbies around here) with DOMDocument::loadand DOMDocument::save.
由于浓汤和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);
}
?>

