$doc = new DOMDocument(); $parent = $doc->createElement('parent'); $child1 = $doc->createElement('child1'); $child2 = $doc->createElement('child2'); $parent->appendChild($child1); $parent->appendChild($child2); $newChild = $doc->createElement('newChild'); $parent->insertBefore($newChild, $child2);
$doc = new DOMDocument(); $parent = $doc->createElement('parent'); $child1 = $doc->createElement('child1'); $child2 = $doc->createElement('child2'); $parent->appendChild($child1); $parent->appendChild($child2); $newChild = $doc->createElement('newChild'); $newChild->setAttribute('class', 'new-class'); $parent->insertBefore($newChild, $child2);In this example, we create a parent element and two child elements. We append both the child elements to the parent element. Then, we create a new child element and set an attribute on it. We insert this new element with the attribute before the second child element using the `insertBefore` method. The `insertBefore` method is part of the PHP DOM extension library.