6

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.

1
  • 1
    You're looking for the insertBefore method I presume, just search for the shop element and insert before that. Commented Jan 18, 2011 at 11:59

3 Answers 3

7

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to Rik I came to the above solution with getElementsByTagName . Thanks to everyone else for the lightning quick responses.
0

Fetch the <shop> node and use

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);

Comments

0

Try

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

where $shop points to the <shop> element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.