Tutorial :How can I move XML elements with PHP's SimpleXML?


How can I move an xml element elsewhere in a document? So I have this:

<outer>      <foo>          <child name="a"/>          <child name="b"/>          <child name="c"/>      </foo>      <bar />  </outer>  

and want to end up with:

<outer>      <foo />      <bar>          <child name="a"/>          <child name="b"/>          <child name="c"/>      </bar>  </outer>  

Using PHP's simpleXML.

Is there a function I'm missing (appendChild-like)?


You could make a recusrive function that clones the attributes and children. There is no other way to move the children with SimpleXML


class ExSimpleXMLElement extends SimpleXMLElement {      //ajoute un object à un autre      function sxml_append(ExSimpleXMLElement $to, ExSimpleXMLElement $from) {          $toDom = dom_import_simplexml($to);          $fromDom = dom_import_simplexml($from);          $toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));      }  }          $customerXML = <<<XML      <customer>          <address_billing>              <address_book_id>10</address_book_id>              <customers_id>20</customers_id>              <telephone>0120524152</telephone>              <entry_country_id>73</entry_country_id>          </address_billing>          <countries>              <countries_id>73</countries_id>              <countries_name>France</countries_name>              <countries_iso_code_2>FR</countries_iso_code_2>          </countries>      </customer>      XML;    $customer = simplexml_load_string($customerXML, "ExSimpleXMLElement");  $customer->sxml_append($customer->address_billing, $customer->countries);    echo $customer->asXML();          <?xml version="1.0"?>      <customer>          <address_billing>              <address_book_id>10</address_book_id>              <customers_id>20</customers_id>              <telephone>0120524152</telephone>              <entry_country_id>73</entry_country_id>              <countries>                 <countries_id>73</countries_id>                 <countries_name>France</countries_name>                 <countries_iso_code_2>FR</countries_iso_code_2>              </countries>          </address_billing>      </customer>  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »