Search code examples
phpxmlfilesimplexml

write record into xml file via simplexml?


$xmldbase = simplexml_load_file($xmlfile);
$date = date();

$id = (integer) $xmldbase['id'];
$xmldbase['id'] = $id+1;

$xmlString = "
    <player>
        <id>$id</id>
        <name>$name</name>
        <date>$date</date>
        <score>$score</score>
        <right>$rightA</right>
        <false>$falseA</false>
        <ip>$ip</ip>
    </player>";

$xmldbase = new SimpleXMLElement($xmlString);

$xmldbase->asXML($xmlfile);

This works so far but does not add the node player to my file its overwritten. But how I can add my player node? The example does not load a file (https://www.php.net/manual/de/simplexmlelement.addchild.php) where should add the data?


Solution

  • The code is similar to:

    $xmldbase = simplexml_load_file($xmlfile);
    $date = date();
    
    $id = (integer) $xmldbase['id'];
    $xmldbase['id'] = $id+1;
    
    // add new `player` node to root xml-element
    $player = $xmldbase->addChild('player');
    // add `id` node to just created `player` node
    $player->addChild('id', $id);
    // add `name` node to just created `player` node
    $player->addChild('name', $name);
    // add other nodes here
    
    $xmldbase->asXML($xmlfile);