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

255 views Asked by At

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?

1

There are 1 answers

1
Marcel On BEST ANSWER

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. ;)