2

This is my starting xml :

 <?xml version="1.0" encoding="utf-8"?>
    <root>
      <child>
        <children></children>
     </child>
    </root>

and I wanna add other children in child?? but I'm trying and nothing I don't know how... :S help pls I want to my xml be to like this

  <?xml version="1.0" encoding="utf-8"?>
    <root>
      <child>
        <children></children>
        <children></children>
     </child>
    </root>

Here is my code :

<?php
            $dom = new DomDocument;
            //$dom->preserveWhiteSpace = FALSE;
            $dom->load("myXML.xml");
            $root = $dom->getElementById('root');
            $params = $dom->getElementsByTagName('child');
            $cantidadCategorias = $params->length+1;

            $newElement = $dom->createElement('child','');
            $dom->appendChild($newElement);
            $f = fopen("myXML.xml",'w+'); 
            fwrite($f,$dom->saveXML()); 
            fclose($f); 
Midhun
  • 1,107
  • 10
  • 24
Kucho Alejandro
  • 63
  • 1
  • 1
  • 6

3 Answers3

8

With DOMDocument it's as easy as this:

$child = new DOMElement('children');
$parent->appendChild($child);

Whereas $parent is the DOMElement parent which (after you have updated your question) to aquire is part of your problem:

// append <children> to the first <child> element
$parent = $dom->getElementsByTagName('child')->item(0);
$child = new DOMElement('children');
$parent->appendChild($child);
hakre
  • 193,403
  • 52
  • 435
  • 836
  • See that line: `$parent = $dom->getElementsByTagName('child')->item(0);` – hakre Mar 14 '12 at 17:20
  • 1
    Excelent dude ty with getELementByTagName()->item :D – Kucho Alejandro Mar 14 '12 at 17:24
  • An additional tip: instead of `fopen`... you can just use [`DOMDocument::save()`](http://php.net/manual/en/domdocument.save.php) - that's the counterpart to `DOMDocument::load()` you use at the top. – hakre Mar 14 '12 at 17:27
0

Since you have tagged php i am assuming you are looking for a solution in PHP did you try the following:

$myxml = new SimpleXMLElement($xmlstr);
$myxml->child[0]->addChild('children');

See: http://www.php.net/manual/en/simplexml.examples-basic.php for a good set of examples on XML manipulation in PHP

Vijay Agrawal
  • 3,751
  • 2
  • 23
  • 25
0

Some good examples on how to append XML nodes can be found in the PHP manual. Like this one on how to use the SimpleXMLElement class to add a child node.

Thomas Bates
  • 677
  • 4
  • 15