2

Is it possible to insert a PHP SimpleXMLElement as a child of another Element

$xml   = new SimpleXMLElement('<root/>');
$xml_a = new SimpleXMLElement('<parent/>');
$xml_b = new SimpleXMLElement('<child/>');
$xml_b->addAttribute('attribute','value');
$xml_b->addChild('item','itemValue');
// the part will cause and error
$xml_a->addChild($xml_b);
$xml->addChild($xml_a);

I know the above code doesn't work, but that would be the sort of thing I'm looking for.

So that the structure looks like:

<root>
 <partent>
  <child attribute="value">
   <item>itemValue</item>
  </child>
 </parent>
</root>

I have tried using something like the below to addChild() :

$dom = dom_import_simplexml($xml_a);
$_xml_ = $dom->ownerDocument->saveXML($dom->ownerDocument->documentElement);
$xml->addChild('parent',$_xml_);

The solution im sure is relatively simple, but I've not used SimpleXMLElement like this before.

Deano
  • 145
  • 1
  • 11
  • 1
    Possible duplicate of [PHP SimpleXML: insert node at certain position](http://stackoverflow.com/questions/3361036/php-simplexml-insert-node-at-certain-position) – Sherif Sep 16 '16 at 10:34

1 Answers1

2

You can't with SimpleXML, but if you really need manipulate your DOM or create it from scratch consider DOMDocument.

$xmlObject   = new \DOMDocument();
$xml = $xmlObject->createElement('root');
$xml_a = $xmlObject->createElement('parent');
$xml_b = $xmlObject->createElement('child');
$xml_b->setAttribute('attribute','value');
$xml_b->appendChild(new \DOMElement('item', 'itemValue'));
$xml_a->appendChild($xml_b);
$xml->appendChild($xml_a);
$xmlObject->appendChild($xml);
echo $xmlObject->saveXML();
jakub wrona
  • 2,212
  • 17
  • 17