2013-09-30 54 views
1

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

我该如何解决这个问题?

回答

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

+0

谢谢,但没有奏效。 –

+0

答复已更新。对不起,我把它叫做错误的DOM对象。在加载文件的对象上设置“preserveWhiteSpace = false”(我想应该在加载之前),你应该没问题。 –

+0

是的,它做到了。谢谢。 –