Reputation: 4634
I was trying to recover the XML file back and add a new element, but it seems to miss the '\n' in the end.
For example, the original file is like
$doc = new DOMDocument;
$doc->formatOutput = true;
$node = $doc->createElement("root");
$ele = $doc->createElement("first-ele", 'ele1');
$node->appendChild($ele);
$ele2 = $doc->createElement("sec-ele", 'ele2');
$node->appendChild($ele2);
$doc->appendChild($node);
$data_string = $doc->saveXML();
echo $doc->saveXML();
The output is nice.
<?xml version="1.0"?>
<root>
<first-ele>ele1</first-ele>
<sec-ele>ele2</sec-ele>
</root>
However, I want to add a new element within the root tag.
$new_doc = new DOMDocument;
$new_doc->loadXML($data_string);
$new_doc->formatOutput = true;
$root = $new_doc->getElementsByTagName('root')->item(0);
$new_element = $new_doc->createElement('third-ele', 'third');
$root->appendChild($new_element);
echo $new_doc->saveXML();
The output seems to miss the breakline.
<?xml version="1.0"?>
<root>
<first-ele>ele1</first-ele>
<sec-ele>ele2</sec-ele>
<third-ele>third</third-ele></root>
Demo ~ https://3v4l.org/PFk10
Upvotes: 1
Views: 54
Reputation: 19492
The parser preserves whitespaces by default. They are put into text nodes. The root
element node has five child nodes, actually. The two elements and three text nodes for the line breaks and indents.
Now you're adding the 3rd element node after the last whitespace text node. The serializer recognizes the mixed type child nodes and does not add additional whitespaces (They could change/break the meaning: <first-char>W</first-char>ord
vs <first-char>W</first-char> ord
).
Here is a property DOMDocument::preserveWhiteSpace
that you can set to false before loading the XML. In this case the parser will not create any whitespace text nodes and the child nodes will not be of mixed type.
$new_doc = new DOMDocument;
$new_doc->preserveWhiteSpace = false;
$new_doc->loadXML($data_string);
$new_doc->formatOutput = true;
$root = $new_doc->documentElement;
$new_element = $new_doc->createElement('third-ele', 'third');
$root->appendChild($new_element);
echo $new_doc->saveXML();
Upvotes: 1