1

I need to add in a new root node to the following XML

<?xml version="1.0"?>
<unit>
<source> 
<id>ANCH02</id> 
<uri>http://www.hamiltonisland.biz/tabid/339/Default.aspx</uri> 
</source>
</unit>

to become

<?xml version="1.0"?>
        <units>
        <unit>
        <source> 
        <id>ANCH02</id> 
        <uri>http://www.hamiltonisland.biz/tabid/339/Default.aspx</uri> 
        </source>
        </unit>
        </units>

How could I do this? It doesn't seem like SimpleXMLElement has this functionality. I have also looked at this DomNode example http://php.net/manual/en/domnode.insertbefore.php but it doesnt seem to be able to add in a new root node.

1

2 Answers 2

4

This seem to work

$units = $dom->createElement('units');
$units->appendChild($dom->documentElement);
$dom->appendChild($units);

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

DOMDocument:

$yourDOMDOMDocument ... <--- already loaded XML
$doc = new DOMDocument();
$doc->appendChild($doc->createElement('Units'));
$doc->documentElement->appendChild($doc->importNode($yourDOMDocument->documentElement));

Or. if you have your XML as SimpleXMLElement already:

$yourSimpleXML ... <--- already loaded XML
$doc = new DOMDocument();
$doc->appendChild($doc->createElement('Units'));
$domnode = dom_import_simplexml($yourSimpleXML);
$doc->documentElement->appendChild($doc->importNode($domnode));
//if you want it back as SXE:
$newSimpleXMLElement = simplexml_import_dom($doc);

Comments

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.