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.

1

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Working like a charm :) one question. The xml header shows as <?xml version="1.0"?> can i influence that so as to set the attribute encoding="UTF-8"
Yes, $xmlObject = new \DOMDocument('1.0', 'UTF-8');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.