通过PHPDOM操作添加新的XML元素

Add new XML element through PHP DOM Manipulation

我正在尝试向此 XML 文档添加一个名为 member 的新 XML 元素:

<?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>

这是我的 php 脚本:

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();
    }

不幸的是,当我 print $dom->saveXML(); 那个新元素没有被插入 DOM 时,它确实打印了:

JohnSmith12HankRogers18JoeAshton21

如果您检查输出 XML,您会在末尾看到一个空的 <member/>,因为您没有将任何子元素附加到 $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();
}