In this example, we will load XML file and convert it into an array in Laravel application. Before we starts let's know more about XML.
The XML stands for Extensible Markup Language. It's a markup language like HTML to store and transmit data. It has per-defined rules for encoding document in format. It's text based format to store structured data into file. We can store data like book information, student data, documents or configurations into it.
XML is popular because it stores data into text format so there is no hardware or software dependencies to read or alter data.
For this example, we will use simplexml_load_string() function to create XML object from file. It will work on all versions of Laravel like Laravel 6, Laravel 7, Laravel 8 and Laravel 9.
First of all, let's create XML file into our file system or you can use any existing XML file for this example. We will create XML file
If you don't have any xml file then copy upper code and paste into text-editor and save as employees.xml at public folder.
In Laravel, you can read XML file data into any class like Controller, Model, Seeder or etc. Here, we will use controller to read XML data. So open any controller from your application and place below code into it.
This function will use file_get_contents() function to read file as normal file and gets data from that file to object. Then we will create XML object from that file content and lastly we will encode and decode XML data as JSON so it will return array data.
Here, we just print data into browser screen. But you can use it as per your requirements like store into database or perform some calculation on that data or display it as table into webpage. So it's up to you, How you are gonna use it.
Below code snippet is showing output of XML data using dd() function.
In this example, we have created an XML file and read that file into Laravel using in-built PHP functions. It will works on core PHP too but you need to modify some things like giving a full path while reading. Still, if you have any queries feel free to place a comment below.
Ask anything about this examples