SimpleXML is a PHP extension that allows us to easily manipulate and get XML data.
The SimpleXML Parser
SimpleXML is a tree-based parser.
SimpleXML provides an easy way of getting an element's name, attributes and textual content if you know the XML document's structure or layout.
SimpleXML turns an XML document into a data structure you can iterate through like a collection of arrays and objects.
Compared to DOM or the Expat parser, SimpleXML takes a fewer lines of code to read text data from an element.
Installation
From PHP 5, the SimpleXML functions are part of the PHP core. No installation is required to use these functions.
PHP SimpleXML - Read From String
The PHP simplexml_load_string[]
function is used to read XML data from a string.
Assume we have a variable that contains XML data, like this:
$myXMLData =
"
Tove
Jani
Reminder
Don't forget me this weekend!
";
The example below shows how to use the simplexml_load_string[]
function to read XML data from a string:
Example
Run example »
The output of the code above will be:
SimpleXMLElement Object [ [to] => Tove [from] => Jani [heading] => Reminder [body] => Don't forget me this weekend! ]
Error Handling Tip: Use the libxml functionality to retrieve all XML errors when loading the document and then iterate over the errors. The following example tries to load a broken XML string:
Example
Run example »
The output of the code above will be:
Failed loading XML:
Opening and ending tag mismatch: user line 3 and wronguser
Opening and ending tag mismatch: email line 4 and wrongemail
PHP SimpleXML - Read From File
The PHP simplexml_load_file[]
function is used to read XML data from a file.
Assume we have an XML file called "note.xml", that looks like this:
Tove
Jani
Reminder
Don't forget me this weekend!
The example below shows how to use the simplexml_load_file[]
function to read XML data from a file:
Example
Run example »
The output of the code above will be:
SimpleXMLElement Object [ [to] => Tove [from] => Jani [heading] => Reminder [body] => Don't forget me this weekend! ]
Tip: The next chapter shows how to get/retrieve node values from an XML file with SimpleXML!
More PHP SimpleXML
For more information about the PHP SimpleXML functions, visit our PHP SimpleXML Reference.
In this post, you'll learn how to parse XML into an array in PHP. SimpleXML is a PHP extension that makes this possible.
In your day-to-day PHP development, sometimes you'll need to deal with XML content. Whether it’s exporting data as XML documents or processing incoming XML documents in your application, it’s always handy to have a
library that can perform these operations smoothly. When it comes to dealing with XML in PHP, there are different methods to choose from. In fact, there are different extensions available in PHP that allow you to read and parse XML documents.
PHP’s XML parser is based on James Clark’s expat library, which is a stream-oriented XML library written in C. This XML parser library allows you to parse XML documents, but it’s not able to validate them. It’s event-based and stream-oriented, and
thus it’s really useful when you’re dealing with very large XML files—but a little more complicated than it needs to be for small files.
The other option is the SimpleXML extension, which is one of the most popular extensions used by the PHP community to process XML documents. The SimpleXML extension allows you to parse XML documents very easily, just as if you were reading a file in PHP.
In this article, we’re going to use the SimpleXML extension to demonstrate how you could convert XML content into an array. If you want to follow along with the example in this article, make sure that you’ve installed the SimpleXML extension in your PHP installation.
The SimpleXML PHP Extension
The SimpleXML PHP extension provides a complete toolset which you can use to read, write and parse XML documents in your PHP applications. It’s important to note that the SimpleXML extension requires PHP 5 at a minimum. Also, it requires the libxml PHP extension.
The
SimpleXML extension is enabled by default, but if you want to check if it's enabled in your PHP installation, you can check it quickly by using the phpinfo[]
function.
As you can see, you should see the SimpleXML section in the output of the phpinfo[]
function.
The SimpleXML extension provides different functions that you could use to read and parse XML content.
Loading an XML String or File With SimpleXML
For example,
if you want to parse the XML file, you can use the simplexml_load_file[]
function. The simplexml_load_file[]
function allows you to read and parse the XML file in a single call. On the other hand, if you have an XML string which you want to convert into an XML document object, you can use the simplexml_load_string[]
function.
You could also use the file_get_contents[]
function to read the file contents and pass the resulting string to the simplexml_load_string[]
function, which eventually parses it into an object. Alternatively, if you
prefer the object-oriented way, you could also use the SimpleXMLElement
class and its utility methods to convert an XML string into an object.
In this article, we’re going to use the simplexml_load_file[]
function to read an XML file, and we’ll see how to convert it into an array. Next, we’ll go through a real-world example to demonstrate how to do this.
How to Convert XML to an Array With PHP
In this section, we’ll see how you can convert XML content into an array.
First of all, let’s quickly go through the steps that you need to follow to convert XML content into an array with the help of the SimpleXML extension.
- Read the file contents and parse them. At the end of this step, the content is parsed and converted into the
SimpleXMLElement
object format. We’re going to use thesimplexml_load_file[]
function to achieve this. - Next, you need to convert the
SimpleXMLElement
object into a JSON representation by using thejson_encode[]
function. - Finally, you need to use the
json_decode[]
function to decode the JSON content so that it eventually generates an array of all documents.
For demonstration purposes, let’s assume that we have an XML file as shown in the following snippet. We’ll call it employees.xml. It contains the basic details of all employees. Our aim is to convert it into an array that you could use for further processing.
John 3201 Glendale Avenue Los Angeles CA Mike 781 Stroop Hill Road Duluth GA
As you can see, the employees.xml file contains the names and emails of employees.
It’s important to note that the employee-id
value is passed as an attribute of the tag.
Next, create the simplexml.php file with the following contents.
Let’s go through the important snippets in the above example to understand how it works.
Read and Parse the XML File
Firstly, we’ve used the libxml_use_internal_errors[]
function to disable standard libxml errors and enable user error handling. In this way, we can catch the XML errors during parsing
and display them in a user-friendly way. This is also really useful in the development phase.
Next, we’ve used the simplexml_load_file[]
function to read and parse the employees.xml file. The first argument of the simplexml_load_file[]
function is a path to the XML file. It’s important to note that you need to adjust this path as needed. In the above example, it’s assumed that the employees.xml file is at the same directory level as that of the
simplexml.php file. If the XML file is parsed successfully, it returns an object of the SimpleXMLElement
class; otherwise, it returns FALSE
.
Next, if the $objXmlDocument
variable is set to FALSE
, there was a problem parsing the employees.xml file. In that case, we use the libxml_get_errors[]
function to get all the errors and display them for debugging purposes. The $objXmlDocument
variable is set to TRUE
if the employees.xml file is parsed
successfully.
Convert the SimpleXMLElement
Object Into Its JSON Representation
Next, we’ve used the json_encode[]
function to convert the SimpleXMLElement
object into its JSON representation. We’ve stored the JSON string in the $objJsonDocument
variable, as shown in the following snippet.
$objJsonDocument = json_encode[$objXmlDocument];
Decode the JSON String Into an Array
Finally, we’ve used the json_decode[]
function to decode the JSON string data. It’s important to note that we’ve passed TRUE
in the second argument of the
json_decode[]
function, which converts all objects into associative arrays.
$arrOutput = json_decode[$objJsonDocument, TRUE];
Had you not passed TRUE
in the second argument, the json_decode
function would have produced objects of type StdClass
instead of arrays.
So that's an outline of the whole process. Let’s run the simplexml.php file, and you should see the following output.
Array [ [employee] => Array [ [0] => Array [ [@attributes] => Array [ [id] => 1 ] [name] => John [email] => [address] => Array [ [street] => 3201 Glendale Avenue [city] => Los Angeles [state] => CA ] ] [1] => Array [ [@attributes] => Array [ [id] => 2 ] [name] => Mike [email] => [address] => Array [ [street] => 781 Stroop Hill Road [city] => Duluth [state] => GA ] ] ] ]
As expected, the array contains all the documents. As you may have noticed, it has also parsed the id
field,
which is attached with each document in the form of an attribute, and you can access it with the @attributes
key, as shown in the above output. Basically, everything is available in the form of key-value pairs. So you have a complete array at your disposal for further processing.
So that’s how you can convert XML content into an array in PHP. It was a very simple example, but it should give you some insight into the whole process.
Conclusion
In this article, we discussed how
to convert an XML file into an array using PHP and SimpleXML. The SimpleXML extension is really useful when it comes to parsing and manipulating XML documents.
The Best PHP Scripts on CodeCanyon
The free libraries on Packagist are wonderful for basic functionality—the foundation for a good app. However, for more specialized features or for complete applications that you can use and customize, take a look at the professional PHP scripts on CodeCanyon.
Explore thousands of the best and most useful PHP scripts ever created on CodeCanyon.
Here are a few of the best-selling and up-and-coming PHP scripts available on CodeCanyon for 2020.
Learn PHP With a Free Online Course
If you want to learn PHP, check out our free online course on PHP fundamentals!
In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming [OOP].
Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.
Did you find this post useful?
Software Engineer, FSPL, India
I'm a software engineer by profession, and I've done my engineering in computer science. It's been around 14 years I've been working in the field of website development and open-source technologies. Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I've worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I've also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce. I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore [India] and 2018 DrupalCon which was held in Mumbai [India]. Apart from this, I like to travel, explore new places, and listen to music!