PHP XML inserting element after (or before) another element

后端 未结 3 445
再見小時候
再見小時候 2020-11-30 14:19

I have a previously generated XML like this:



    
相关标签:
3条回答
  • 2020-11-30 14:41

    Try

    $section = $dom->documentElement->insertBefore(
        $dom->createElement('section'), 
        $shop)
    );
    

    where $shop points to the <shop> element.

    0 讨论(0)
  • 2020-11-30 14:49

    Fetch the <shop> node and use

    • DOMNode::insertBefore — Adds a new child before a reference node

    instead of appending to the documentElement.

    You can do that from the DOMDocument as well when passing in the shop node as second argument. Personally, I find it easier to just do that from the shop node because you have to fetch it anyway:

    $shopNode->insertBefore($newNode);
    
    0 讨论(0)
  • 2020-11-30 14:51

    You might try this; I didn't test it, but the solution comes from using insertBefore instead of appendChild.

    $shop = $dom->getElementsByTagName("shop")->item(0);
    $section = $dom->documentElement->insertBefore($dom->createElement('section'),$shop);
    
    0 讨论(0)
提交回复
热议问题