Search code examples
phpxmlsimplexml

PHP XML addChild() not working


I'm working on project, one of its functions is to add data to XML file that will be extracted later, the extracting part is working well but not the adding part. I created a new php file that contains the code of XML adding part, but still not working. Here is the php file:

<?
$xml = simplexml_load_file('test.xml');
$msg = $xml->addChild('msg');
$msg->addChild('name', 'newName');
$msg->addChild('text', 'myText');
?>

Here is the test.xml file:

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

</msgs>

The page shows no php error and the xml still the same. I have been looking for solution for hours but couldn't find. Please help!


Solution

  • simplexml_load_file() returns a SimpleXMLElement to which you're adding elements, you now need to serialise that instance back to a file:

    $msg->asXML('output.xml');
    

    Or if you just want to capture the XML as a string:

    $xmlString = $msg->asXML();