0

I'm trying to add a child to an Simple XML object, but when an element with the same name already exists on that level it doesn't get added.

Here's what I'm trying:

$str = '<?xml version="1.0"?>
    <root>
        <items>
            <item></item>
        </items>
    </root>';

$xml = new SimpleXMLElement($str);
$xml->addChild('items');
print $xml->asXML();

I get the exact same xml as I started with, when what I really want is a second empty items element. If I use another element name than it does get added.

leon.nk
  • 437
  • 2
  • 6
  • 15
  • In `print $xml->asXML();` what is `asXML()`; Try this: `print_r($xml);` – Vimalnath Jun 28 '12 at 11:47
  • 1
    Your example code works very well for me: http://codepad.viper-7.com/ydvjGD – Niko Jun 28 '12 at 12:10
  • possible duplicate of [A simple program to CRUD node and node values of xml file](http://stackoverflow.com/questions/4906073/a-simple-program-to-crud-node-and-node-values-of-xml-file) – Gordon Jun 28 '12 at 12:17

2 Answers2

1

Use this code for adding a new items node in your example:

$str = '<?xml version="1.0"?>
<root>
    <items>
        <item></item>
    </items>
</root>';

$xml = new SimpleXMLElement($str);
$xml->addChild('items', '');
var_dump($xml->asXML());

Which outputs:

string '<?xml version="1.0"?>
<root>
    <items>
        <item/>
    </items>
<items></items></root>
' (length=109)
Jevgenij Evll
  • 1,892
  • 18
  • 21
0

You could use simpleloadxml as alternate

$xml = simplexml_load_file("myxml.xml");
$sxe = new SimpleXMLElement($xml->asXML());
$itemsNode = $sxe->items[0];
$itemsNode->addChild("item", $newValue);
$sxe->asXML("myxml.xml"); 
Vimalnath
  • 6,373
  • 2
  • 26
  • 47