Как я могу переместить элементы XML с помощью PHP SimpleXML? - PullRequest
0 голосов
/ 20 июля 2010

Как я могу переместить элемент xml в другое место в документе? Итак, у меня есть это:

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

и хочу в итоге:

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

Использование PHP SimpleXML.

Есть ли функция, которую я пропускаю (по типу appendChild)?

Ответы [ 2 ]

1 голос
/ 20 июля 2010

Вы можете сделать функцию recusrive, которая клонирует атрибуты и дочерние элементы.Нет другого способа move детей с SimpleXML

0 голосов
/ 01 октября 2018
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>
...