PHP XML insertion element after (or before) another element

I have previously created XML, for example:

<newsletter>

    <header>
        </magazine>
        </image>
        <strap/>
    </header>

    <intro>
        <date/>
        <text/>
        </edimg>
    </intro>

    <shop>
        <heading/>
        <article/>
        <title/>
        <img/>
        <link/>
        <excerpt/>
    </shop>

    <sidebar>
        <cover/>
        <cover_link/>
        <text/>
        <advert>
        <link/>
        <image/>
        </advert>
    </sidebar>

</newsletter>

I need to be able to insert an element between elements <intro>and<shop>

$section = $dom->documentElement->appendChild($dom->createElement('section'));

just create an element inside <newsletter>.

I suggested that it would be quite simple, but it seems it cannot find a solution.

Thank.

+3
source share
3 answers

You can try this; I have not tested 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);
+4
source

Extract <shop>node and use

instead of adding to documentElement.

DOMDocument, node . node, :

$shopNode->insertBefore($newNode);
0

Try

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

where $shoppoints to an element <shop>.

0
source

Source: https://habr.com/ru/post/1786122/


All Articles