How to replace XML node with SimpleXMLElement PHP -


i have following xml (string1):

<?xml version="1.0"?> <root>    <map>       <operationallayers>          <layer label="security" type="feature" visible="false" useproxy="true" usepopup="all" url="http://stackoverflow.com"/>       </operationallayers>    </map> </root> 

and have piece of xml (string2):

<operationallayers>     <layer label="teste1" type="feature" visible="false" useproxy="true" usepopup="all" url="http://stackoverflow.com"/>     <layer label="teste2" type="dynamic" visible="false" useproxy="true" usepopup="all" url="http://google.com"/> </operationallayers> 

i used funcion simplexml_load_string import both respectives var:

$xml1 = simplexml_load_string($string1); $xml2 = simplexml_load_string($string2); 

now, want replace node 'operationallayers' of string1 node 'operationallayers' of string2, how?

the class simplexmlelement not have method 'replacechild' dom has.

similar has been outlined in simplexml: append 1 tree another can import nodes domdocument because write:

"the class simplexmlelement dont have method 'replacechild' dom."

so when import dom can use those:

$xml1 = simplexml_load_string($string1); $xml2 = simplexml_load_string($string2);  $domtochange = dom_import_simplexml($xml1->map->operationallayers); $domreplace  = dom_import_simplexml($xml2); $nodeimport  = $domtochange->ownerdocument->importnode($domreplace, true); $domtochange->parentnode->replacechild($nodeimport, $domtochange);  echo $xml1->asxml(); 

which gives following output (non-beautified):

<?xml version="1.0"?> <root>    <map>       <operationallayers>     <layer label="teste1" type="feature" visible="false" useproxy="true" usepopup="all" url="http://stackoverflow.com"/>     <layer label="teste2" type="dynamic" visible="false" useproxy="true" usepopup="all" url="http://google.com"/> </operationallayers>    </map> </root> 

additionally can take , add operation simplexmlelement it's wrapped. works extending simplexmlelement:

/**  * class mysimplexmlelement  */ class mysimplexmlelement extends simplexmlelement {     /**      * @param simplexmlelement $element      */     public function replace(simplexmlelement $element) {         $dom     = dom_import_simplexml($this);         $import  = $dom->ownerdocument->importnode(             dom_import_simplexml($element),             true         );         $dom->parentnode->replacechild($import, $dom);     } } 

usage example:

$xml1 = simplexml_load_string($string1, 'mysimplexmlelement'); $xml2 = simplexml_load_string($string2);  $xml1->map->operationallayers->replace($xml2); 

related: in simplexml, how can add existing simplexmlelement child element?.

last time extended simplexmlelement on stackoverflow in answer "read , take value of xml attributes" question.


Comments