Following up from my previous question.
I am using addChild()
to add another <comment>
element as a child of the root element. I used the code from this question:
$file = "comments.xml";
$comment = $xml -> comment;
$comment -> addChild("user","User2245");
$comment -> addChild("date","02.10.2018");
$comment -> addChild("text","The comment text goes here");
$xml -> asXML($file)
Now, when I echo the file contents:
foreach($xml -> children() as $comments) {
echo $comments -> user . ", ";
echo $comments -> date . ", ";
echo $comments -> text . "<br>";
}
I only get the old file contents (with no changes):
User4251,02.10.2018,Comment body goes here
User8650,02.10.2018,Comment body goes here
I am using the same comments.xml file. There are no errors displayed.
Why doesn't the child element get appended?
You are adding to one of the comment
elements, add it to the full doc.
$xml = new simplexmlelement('<?xml version="1.0" encoding="utf-8"?>
<comments><comment>
<user>User4251</user>
<date>02.10.2018</date>
<text>Comment body goes here</text>
</comment>
<comment>
<user>User8650</user>
<date>01.10.2018</date>
<text>Comment body goes here</text>
</comment></comments>');
$child = $xml->addchild('comment');
$child->addChild("user","User2245");
$child->addChild("date","02.10.2018");
$child->addChild("text","The comment text goes here");
echo $xml->asXML();