Search code examples
phpxmlxsdsimplexml

SimpleXML add element before


I'm using SimpleXML to generate xml based invoice.

The structure has to be like this (heavily simplified):

<invoice>
    <total>
        <price>100</price>
    </total>
    <items>
        <item>...</item>
    </items>
</invoice>

But if first loop my items and add totals together, and then insert <total>:

<invoice>
    <items>...</items>
    <total>...</total>
</invoice>

But CUSTOM XSD says it invalid. This probably will not cause an error in applications, but I'd like it to be valid.

So can I insert <total> tag before <items> tag?

Note: <items> tag is not the first element in <invoice>.

Jquery equivalent of the function in need is .insertBefore()

Cheers!


Solution

  • You can do something like this:

        $domelement = dom_import_simplexml($items);
    
        $new = $dom->insertBefore(
            $dom->ownerDocument->createElement("total"),
            $dom->firstChild
        );
    
        $newsxml = simplexml_import_dom($new);
    

    then add the items into total node.