我需要在新的根节点中添加以下XML
<?xml version="1.0"?>
<unit>
<source>
<id>ANCH02</id>
<uri>http://www.hamiltonisland.biz/tabid/339/Default.aspx</uri>
</source>
</unit>
成为
<?xml version="1.0"?>
<units>
<unit>
<source>
<id>ANCH02</id>
<uri>http://www.hamiltonisland.biz/tabid/339/Default.aspx</uri>
</source>
</unit>
</units>
我怎么能这样做?看起来SimpleXMLElement没有这个功能。我也看过这个DomNode示例http://php.net/manual/en/domnode.insertbefore.php,但它似乎无法添加新的根节点。
答案 0 :(得分:4)
这似乎有用
$units = $dom->createElement('units');
$units->appendChild($dom->documentElement);
$dom->appendChild($units);
答案 1 :(得分:1)
DOM文档:
$yourDOMDOMDocument ... <--- already loaded XML
$doc = new DOMDocument();
$doc->appendChild($doc->createElement('Units'));
$doc->documentElement->appendChild($doc->importNode($yourDOMDocument->documentElement));
或者。如果您已将XML作为SimpleXMLElement:
$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);