附加节点未格式化

时间:2013-09-30 14:54:22

标签: php xml dom dom-node

我制作了一个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');

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

尝试将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::preserveWhiteSpace