1

I am experiencing weird behaviour when trying to format xml output while modifying domdocument structure.

I have created simple Item class based on DomDocument:

class Item extends DOMDocument {
private $root;
function __construct($version = null, $encoding = null) {
 parent::__construct($version, $encoding);
 $this->formatOutput = true;
 $this->root = $this->createElement("root");
 $this->root = $this->appendChild($this->root);
}
function build($name) {
 $item = $this->createElement("item");
 $name = $this->createTextNode($name);
 $item->appendChild($name);
 $this->getElementsByTagName("root")->item(0)->appendChild($item);
}
}

Now, I have small use case here:

$it = new Item('1.0', 'iso-8859-1');
$it->build("first");
$it->build("seccond");
$xml = $it->saveXML();
echo $xml;
$it2 = new Item('1.0', 'iso-8859-1');
$it2->loadXML($xml);
$it2->build("third");
$it2->build("fourth");
$it2->build("fifth");
$it2->formatOutput = true;
$xml2 = $it2->saveXML();
echo $xml2;

And now the odd bit. I call the script and it produces two xml files as required, however I noticed that formating is somehow lost after I edit the document. It sort of carries on without any indents etc.

<?xml version="1.0" encoding="iso-8859-1"?>
<root>
 <item>first</item>
 <item>seccond</item>
</root>
<?xml version="1.0" encoding="iso-8859-1"?>
<root>
 <item>first</item>
 <item>seccond</item>
<item>third</item><item>fourth</item><item>fifth</item></root>

I am assuming it's something I'm missing here. Maybe it's the way I'm appending nodes to root after opening document, maybe some magic setting.

The code does the job, but I was wondering what would be the cause of this weird behaviour.

Cœur
39k25 gold badges207 silver badges282 bronze badges
asked Aug 27, 2010 at 11:15

1 Answer 1

2

You can "tell" libxml that leading/trailing whitespaces are not significant (and thus in this case libxml may insert whitespaces to indent elements) e.g. by setting the preserveWhiteSpace property to false.

$this->formatOutput = true;
$this->preserveWhiteSpace = false;
$this->root = $this->createElement("root");
answered Aug 27, 2010 at 11:21
Sign up to request clarification or add additional context in comments.

1 Comment

I knew it will be something simple :) Thank you, it makes sense and works as expected.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.