[英]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();
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);
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.