Search code examples
phpxmlappendchild

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"?>
<root>
</root>

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
if(isset($xlm->$playerID)){
    echo "Player ID was found.";
}
else{
    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
    $playerElement->appendChild($playerName);

    //add the playerElement to the document
    //THIS IS WHERE THE ERROR OCCURS
    $xml->root->appendChild($playerElement);

    //save and close the document
    $xml->formatOutput = true;
    $xml->save("../../saves/playerPositions.xml");
}

echo "done";

If I just use $xml->appendChild() then I can modify the document, but the new text appears outside of <root></root>.

The exact error is:

Notice: Undefined property: DOMDocument::$root


Solution

  • $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);
    

    eval.in demo 1

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

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

    eval.in 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?):

    if(isset($xlm->$playerID)){
        echo "Player ID was found.";
    }
    

    Replace with getElementsByTagName() :

    if($xml->getElementsByTagName($playerID)->length > 0){
        echo "Player ID was found.";
    }