追加的节点未格式化


Appended nodes not formatted

我做了一个PHP脚本,通过添加新节点来更新现有的XML文件。问题是新节点未格式化。它们写在一行中。这是我的代码:

$file = fopen('data.csv','r');
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$doc = new DOMDocument();
$doc->loadXML(file_get_contents('data.xml'));
$xpath = new DOMXPath($doc);
$root = $xpath->query('/my/node');
$root = $root->item(0);
$root = $xml->importNode($root,true);
// all the tags created in this loop are not formatted, and written in a single line
while($line=fgetcsv($file,1000,';')){
    $tag = $xml->createElement('cart');
    $tag->setAttribute('attr1',$line[0]);
    $tag->setAttribute('attr2',$line[1]);
    $root->appendChild($tag);
}
$xml->appendChild($root);
$xml->save('updated.xml');

我该如何解决这个问题?

尝试将preserveWhiteSpace = FALSE;添加到存储文件的 DOMDocument 对象。

$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML(file_get_contents('data.xml'));
$doc->formatOutput = true;
...

PHP.net - DOMDocument::p reserveWhiteSpace