Question

I made a PHP script that updates an existing XML file by adding new nodes. The problem is that the new nodes are not formatted. They are written in a single line. Here is my code :

$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');

How can I solve this?

Was it helpful?

Solution

Try adding preserveWhiteSpace = FALSE; to DOMDocument object where is file stored.

$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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top