SimpleXML how to prepend a child in a node?

As it’s been mentionned, SimpleXML doesn’t support that so you’d have to use DOM. Here’s what I recommend: extend SimpleXMLElement with whatever you need to use in your programs. This way, you can keep all the DOM manipulation and other XML magic outside of your actual program. By keeping the two matters separate, you improve readability and maintainability.

Here’s how to extend SimpleXMLElement with a new method prependChild():

class my_node extends SimpleXMLElement
{
    public function prependChild($name, $value)
    {
        $dom = dom_import_simplexml($this);

        $new = $dom->insertBefore(
            $dom->ownerDocument->createElement($name, $value),
            $dom->firstChild
        );

        return simplexml_import_dom($new, get_class($this));
    }
}

$actors = simplexml_load_string(
    '<actors>
        <actor>Al Pacino</actor>
        <actor>Zsa Zsa Gabor</actor>
    </actors>',
    'my_node'
);

$actors->addChild('actor', 'John Doe - last');
$actors->prependChild('actor', 'John Doe - first');

die($actors->asXML());

Leave a Comment