Creating an easy XML generator for WooCommerce

We have recently been asked by one of our clients to integrate with SAP. This is Enterprise software that helps to manage general business operations.

Where to begin?

The biggest task for this was giving the ability to output an XML for each order. We began by hooking into the normal WooCommerce Order Processing action.

As you can see above we hooked into ‘woo commerce_order_status_processing’ action. I wanted to make sure that this was the last thing to run, so I had all the information I might need at my disposal.

There are 2 variables being declared, only one of which is being used at the moment, the second was added at a later date (This is explained within the Finishing Touches).

Once you have added the above function we can now begin to set up the XML output. Thankfully we have the filter above. This will allow us to manipulate what is returned.

The nitty gritty of the XML

Below is a complete function that will create the contents of a very small XML. There is minimal output, as the needs for each website will almost definitely be different. I have added comments to the function to explain each step within.

As you can see from the above function we are passing the order object into our filter. We are using DOMDocument to create the XML as opposed to SimpleXML. Both work nicely, although I personally prefer using DOMDocument as you can have more control over everything with various Node Types as well as being a little more forgiving.

Once you have a DOMDocument set, you can begin adding to it. In the above example I only use 2 different functions to build out the XML. These are $xml->createElement( ‘ElementName’, ‘ElementContents’ ); and $parentVariable->appendChild( $childVariable );. These are both pretty self explanatory, one is used to create a new element, this is essentially a group that will hold all the information that is assigned to it. AppendChild is used to assign specific information to an Element.

Below is the XML outputted from the above example:

Nice finishing touches.

As this was for a client we added a few finishing touches to it. We added an order note to each order so the client could easily check whether an XML had been generated. We also hooked into the WooCommerce Order Actions and added the ability to regenerate the XML.

Leave a comment