代码之家  ›  专栏  ›  技术社区  ›  Eric

如何用PHP的simpleXML移动XML元素?

  •  0
  • Eric  · 技术社区  · 14 年前

    如何将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 回复  |  直到 6 年前
        1
  •  1
  •   Nin    14 年前

    你可以做一个复制属性和孩子的恢复功能。没有别的办法 move simpleXML的子级

        2
  •  -1
  •   Joss Eve    6 年前
    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>