Today we are going to see how we can generate an XML file using PHP.
We will be using the easiest way to generate the XML file, which can be a lengthy process and may contain some good amount of code but by following this pattern it would very simple to create and understand the code.
PHP DOM
Assuming, you have basic knowledge of PHP, before we start please take a look at the in-built DOM PHP class, as we going to use this class to create an XML file.
People coming from a core Javascript background would find it super easy, as it is the same Document object that they have been using all the time to create and get HTML elements.
To create the XML file we would be using only 3 functions from the PHP DOM class.
Sample XML File Structure
As an example let’s create an XML for an order placed at some online shop. Let’s keep it simple and have only a few details nested within some XML elements.
The following would be the final structure of the XML file.
<?xml version="1.0" encoding="utf-8"?> <onlineshop> <order> <orderid>1234</orderid> <paymentid>order_wc_1234</paymentid> <status>processing</status> <order_date>processing</order_date> <payment_method>debit card</payment_method> <total>13.45</total> <discount>2.05</discount> <customer> <id>1</id> <firstname>Rupak</firstname> <lastname>Dhiman</lastname> <email>something@email.com</email> <address>120, Some Street Number, Some State, India - 123456</address> <phone>+1234567890</phone> </customer> </order> </onlineshop>
The Workflow
We are going to take it to step by step and create XML elements with the name onlineshop, order & customer.
The very first thing we need is to create an object or instance of the PHP DOM class.
$dom = new DOMDocument( '1.0', 'utf-8' );
After that let us create our very root element using the $dom variable which holds the reference to the DOM object.
$root = $dom->createElement( 'onlinestore' );
Now, the $root variable holds the reference for the root element. To add anything as a child of the root, we first need to create that element and then add that element reference to the $root object.
So, let’s create the order element that is nested inside the root ‘onlinestore‘ element.
$order = $dom->createElement( 'order' ); $root->appendChild( $order );
Save the file
Now, that the $order element has been created we can repeat the steps above and add as many child elements we want to onlinestore or order elements.
After, we done adding the XML elements, we need to add the root element to DOM and save the XML file:
$dom->appendChild( $root ); $file = PATH_TO_THE_DIRECTORY . '/' . sanitize_file_name('order-xml-1234') . '.xml'; $dom->save( $file );
The file would be saved under the path you provided to save the file. Later you can decide according to the flow of your application, what you need to with the saved file.
Putting it all together
Let me know for any issues or suggestions in the comment section.
Happy Coding!