Reputation: 84
I am trying to add children to a newly created node using addChild()
of simpleXml but it gives me an exception:
Warning: SimpleXMLElement::addChild()[simlexmlelement.addchild]: Cannot add child. Parent is not a permanent member of the XML tree in (file address) on line (line number)
And I got that multiple times, since the significant part of my code is:
<?php
$xml = simplexml_load_file(".db.xml") or die("Sorry, no database file found, we will solve it as soon as possible.");
if($xml->$name->getName() == $name) {
echo "We're sorry, but this account name already exists. Underneath is a table with your signup data anyways. We also sent you an email if you are going to retry later.";
} else {
$xml->db->addChild($name);
$xml->$name->addChild("email", $email);
$xml->$name->addChild("day", $day);
$xml->$name->addChild("month", $month);
$xml->$name->addChild("year", $year);
}
?>
And this is my prettified XML code:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<db>
<example>
<email>[email protected]</email>
<day>01</day>
<month>01</month>
<year>1975</year>
</example>
</db>
</body>
What am I doing wrong here?
I know that the values of the variables are not the problem because all variables show the right values in the table of data that I made for the page.
Upvotes: 0
Views: 671
Reputation: 227
You should add the children to a reference like so:
$nametag = $xml->db->addChild($name);
$nametag->addChild("email", $email);
$nametag->addChild("day", $day);
$nametag->addChild("month", $month);
$nametag->addChild("year", $year);
Read more here: http://php.net/manual/ro/simplexmlelement.addchild.php
example nr.1
Update
Here the code I tested with output so you can see it actually adds the tags to the final xml structure:
$xml = simplexml_load_file("db.xml") or die("Sorry, no database file found, we will solve it as soon as possible.");
$name = "a";
$email = "b";
$day = "c";
$month = "d";
$year = "e";
if($xml->$name->getName() == $name) {
echo "We're sorry, but this account name already exists. Underneath is a table with your signup data anyways. We also sent you an email if you are going to retry later.";
} else {
$tagname = $xml->db->addChild($name);
$tagname->addChild("email", $email);
$tagname->addChild("day", $day);
$tagname->addChild("month", $month);
$tagname->addChild("year", $year);
}
var_dump($xml->asXML());
Update 2
To save the xml to a file add at the end:
$xml->asXML("db.xml"); // this would overwrite your old file
Check this out here: http://php.net/manual/en/simplexmlelement.asxml.php
Upvotes: 1