Search code examples
phpxmlxml-documentation

How to get into into another child than 'firstChild' of XML file in PHP?


How can I get through another child of XML file than firstChild in PHP? I have a code like this:

        $root = $xmldoc->firstChild;

Can I simply get into second child or another?


Solution

  • A possible solution to your problem could be something like this. First your XML structure. You asked how to add an item node to the data node.

    $xml = <<< XML
    <?xml version="1.0" encoding="utf-8"?>
    <xmldata>
        <data>
            <item>item 1</item>
            <item>item 2</item>
        </data>
    </xmldata>
    XML;
    

    In PHP one possible solution is the DomDocument object.

    $doc = new \DomDocument();
    $doc->loadXml($xml);
    
    // fetch data node
    $dataNode = $doc->getElementsByTagName('data')->item(0);
    
    // create new item node
    $newItemNode = $doc->createElement('item', 'item 3');
    
    // append new item node to data node
    $dataNode->appendChild($newItemNode);
    
    // save xml node
    $doc->saveXML();
    

    This code example is not tested. Have fun. ;)