user1544522 user1544522 - 1 year ago 148
PHP Question

PHP appendChild to XML root

I know this should be simple, but I'm new to PHP and just do not understand the documentation I've come across. I need a simple explanation.

I have an XML document that I would like to add nodes to. I can add nodes to the document, they only appear outside of the root node and cause errors to happen on subsequent attempts.

Here is my XML:

<?xml version="1.0" encoding="UTF-8"?>

and here is my PHP:

$playerID = "id_" . $_POST['player'];

//load xml file to edit
$xml = new DOMDocument();
$xml->load('../../saves/playerPositions.xml') or die("Error: Cannot load file.");

//check if the player is already in the database
echo "Player ID was found.";
echo "Player ID was not found.";

//so we want to create a new node with this player information
$playerElement = $xml->createElement($playerID, "");
$playerName = $xml->createElement("name", "John Doe");

//add the name to the playerElement

//add the playerElement to the document

//save and close the document
$xml->formatOutput = true;

echo "done";

If I just use
then I can modify the document, but the new text appears outside of

The exact error is:

Notice: Undefined property: DOMDocument::$root

Answer Source

$xml->root isn't the correct way to access root element in this context, since $xml is an instance of DOMDocument (It will work if $xml were SimpleXMLElement instead). You can get root element of a DOMDocument object from documentElement property :

$xml->documentElement->appendChild($playerElement); demo 1

Or, more generally, you can get element by name using getElementsByTagName() :

$xml->getElementsByTagName("root")->item(0)->appendChild($playerElement); demo 2

Further reading : PHP DOM: How to get child elements by tag name in an elegant manner?

That said, this part of your code is also not correct for the same reason (plus a typo?):

    echo "Player ID was found.";

Replace with getElementsByTagName() :

if($xml->getElementsByTagName($playerID)->length > 0){
    echo "Player ID was found.";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download