PHP XML inserting element after (or before) another element
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>
开发者_C百科 </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.
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);
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);
Try
$section = $dom->documentElement->insertBefore(
$dom->createElement('section'),
$shop)
);
where $shop
points to the <shop>
element.
精彩评论