如何使用PHP的SimpleXML移动XML元素?

时间:2010-07-20 14:12:41

标签: php xml simplexml

如何将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-like)?

2 个答案:

答案 0 :(得分:1)

您可以创建一个克隆属性和子元素的递归函数。没有其他办法让move使用SimpleXML

的孩子

答案 1 :(得分:-1)

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>