SimpleXML how to prepend a child in a node?

understack picture understack · Jan 19, 2010 · Viewed 7.7k times · Source

When I call

addChild('actor', 'John Doe');

this child is added in the last. Is there a way to make this new child a first child?

Answer

Josh Davis picture Josh Davis · Jan 19, 2010

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