Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP XML inserting element after (or before) another element

Tags:

dom

php

xml

I have a previously generated XML like this:

<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 in between the <intro> and the <shop> elements

this:

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

will just create the element within <newsletter> .

I assumed this would be fairly simple , but cannot seem to find a solution .

Thanks.

like image 834
BobFlemming Avatar asked Jan 18 '11 11:01

BobFlemming


1 Answers

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);
like image 197
Nabab Avatar answered Nov 06 '22 11:11

Nabab