TheNiceGuy
TheNiceGuy

Reputation: 3730

Add child to specific node

Let's say i have already a XML file which i load like this:

$domtree = new DOMDocument('1.0', 'UTF-8');
$domtree->load('test.xml');

The XML file has a structure like this:

<software>
    <info>
        <version>6.3</version>
    </info>
    <some_stuff>
        <test1>
            <somedata>adsd</somedata>
        </test1>
    </some_stuff>
</software>

How can i add a new element to the decryption?

I tried:

$some_stuff = $domtree->getElementsByTagName('software');
$some_stuff = $some_stuff->getElementsByTagName('some_stuff');
$funcgroup = $some_stuff->appendChild($domtree->createElement('test2'));

PHP Error:

Call to undefined method DOMNodeList::getElementsByTagName()

Upvotes: 0

Views: 200

Answers (2)

mukesh insa
mukesh insa

Reputation: 23

This code will work

$domtree  = new \DomDocument("1.0","UTF-8");
            $xmlfile    = "test.xml";
            $domtree->load($xmlfile);
            $xml_stuff          = $domtree->getElementsByTagName('some_stuff')-> item(0) ;
            $xmlNode1           = $domtree->createElement('test2');
            $xmlNode1           = $xml_stuff->appendChild($xmlNode1);
            $domtree->preserveWhiteSpace = false;
            $domtree->FormatOutput=true;
            $domtree->saveXML();
            $domtree->save($xmlfile);

Upvotes: 1

Ahmed Sagarwala
Ahmed Sagarwala

Reputation: 410

EDITED: I was on the wrong solution...

$domtree is your object. You cannot set $some_stuff to it's value and use it as an object. This is why your getting the undefined method error.

This code will work (although it doesn't quite achieve what you want I think):

$domtree->loadXML(file_get_contents('test.xml'));
$some_stuff = $domtree->getElementsByTagName('software');
$some_stuff = $domtree->getElementsByTagName('some_stuff');
$funcgroup = $domtree->appendChild($domtree->createElement('test2'));

Note how I'm referencing the $domtree object in each line and not the variables you are setting.

Upvotes: 0

Related Questions