Search code examples
phpdomdom-manipulation

Add new XML element through PHP DOM Manipulation


I am trying to add a new XML element called member to this XML document:

<?xml version="1.0" encoding="UTF-8"?>
<members>
    <member id="1" position="president">
        <firstname>John</firstname>
        <surname>Smith</surname>
        <score>12</score>
    </member>
    <member id="2">
        <firstname>Hank</firstname>
        <surname>Rogers</surname>
        <score>18</score>
    </member>
    <member id="3" position="secretary">
        <firstname>Joe</firstname>
        <surname>Ashton</surname>
        <score>21</score>
    </member>
</members>

This is my php script:

function updateDom() {
        $dom = new DOMDocument();
        $dom->preserveWhiteSpace = false;
        $dom->load("members.xml");

        $member = $dom->createElement("member");
        $firstname = $dom->createElement("firstname");
        $surname = $dom->createElement("surname");
        $score = $dom->createElement("score");
        
        $firstnameValue = $dom->createTextNode("New");
        $surnameValue = $dom->createTextNode("New");
        $scoreValue = $dom->createTextNode("New");

        $firstname->appendChild($firstnameValue);
        $surname->appendChild($surnameValue);
        $score->appendChild($scoreValue);

        $dom->documentElement->appendChild($member);
        print $dom->saveXML();
    }

unfortunately when I print $dom->saveXML(); that new element does not get inserted into the DOM, indeed it prints:

JohnSmith12HankRogers18JoeAshton21
  • How can I fix?

Solution

  • If you inspect your output XML you'll see an empty <member/> at the end because you aren't appending any child elements to $member:

    function updateDom() {
        $dom = new DOMDocument();
        $dom->preserveWhiteSpace = false;
        $dom->load("members.xml");
    
        $member = $dom->createElement("member");
        $firstname = $dom->createElement("firstname");
        $surname = $dom->createElement("surname");
        $score = $dom->createElement("score");
    
        $firstnameValue = $dom->createTextNode("New");
        $surnameValue = $dom->createTextNode("New");
        $scoreValue = $dom->createTextNode("New");
    
        $firstname->appendChild($firstnameValue);
        $surname->appendChild($surnameValue);
        $score->appendChild($scoreValue);
    
        // Append child elements
        $member->appendChild($firstname);
        $member->appendChild($surname);
        $member->appendChild($score);
    
        $dom->documentElement->appendChild($member);
        print $dom->saveXML();
    }