How to convert XML to Array or Object in PHP

Code Snippet: XML to Array in PHP

The article explores how to convert XML to array or object in PHP. Here’s a snippet from the article.

<?php
 
$courses_xml =
'&lt;courses>
    &lt;course>
        &lt;title>Fundamentals of Programming&lt;/title>
        &lt;credithours>3 + 1&lt;/credithours>
        &lt;prerequisites>None&lt;/prerequisites>
    &lt;/course>
    &lt;course>
        &lt;title>Object Oriented Programming&lt;/title>
        &lt;credithours>3 + 1&lt;/credithours>
        &lt;prerequisites>Fundamentals of Programming&lt;/prerequisites>
    &lt;/course>
&lt;/courses>';
 
$xml = simplexml_load_string($courses_xml);
$json = json_encode($xml, JSON_PRETTY_PRINT);
$array = json_decode($json, true);
 
?>

That’s just one way of going about this problem. Learn more about this topic in the following sections.

Relevant Content: JSON to XML Conversion

The article  “How to convert XML to JSON in PHP” sets a solid foundation for XML to array in PHP. We suggest reading that article as this article borrows alot from it. We will see that the existing solution adds only one extra function call to get an array or object, and the rest of the code is similar. 

So without any further ado, let’s jump to the main subject.

Scenario: Courses XML data to PHP array

Background & Setup: XML

Suppose we are interacting with an API that responds with some data in XML. The data contains information about some courses. Next, we need to transform this data into PHP arrays or objects, maybe because we are applying some transformational functions that expect an array or object as an argument.

So, let’s see how to go about this problem.

Here’s an XML string readily available in memory. We are not calling any API because it will unnecessarily complicate matters. All that matters is that we understand the process. Data sources can vary.

'&lt;courses>
    &lt;course>
        &lt;title>Fundamentals of Programming&lt;/title>
        &lt;credithours>3 + 1&lt;/credithours>
        &lt;prerequisites>None&lt;/prerequisites>
    &lt;/course>
    &lt;course>
        &lt;title>Object Oriented Programming&lt;/title>
        &lt;credithours>3 + 1&lt;/credithours>
        &lt;prerequisites>Fundamentals of Programming&lt;/prerequisites>
    &lt;/course>
&lt;/courses>'

Option 1: Convert XML to Array in PHP

As mentioned, the code largely remains the same as in the previous article about XML to JSON in PHP. We need to call the decoding function to convert JSON to an array. The following illustration clarifies it.

If you notice, the flow is the same as already seen in XML to JSON except for the additional last decoding step. The JSON serves as an intermediate link between the two. 

Let’s jump to the first step and read the XML string through the simplexml_load_string function. This function returns an instance of SimpleXMLElement.

$xml = simplexml_load_string($courses_xml);

After this step, we will move on to json_encode to get the intermediate JSON representation.

$json = json_encode($xml);

Now, as we have the JSON it is super easy to transform it into an array as follows.

$array = json_decode($json, true);

The boolean argument is necessary else the function returns an object. Let’s put all of this together.

<?php
 
$courses_xml =
'&lt;courses>
    &lt;course>
        &lt;title>Fundamentals of Programming&lt;/title>
        &lt;credithours>3 + 1&lt;/credithours>
        &lt;prerequisites>None&lt;/prerequisites>
    &lt;/course>
    &lt;course>
        &lt;title>Object Oriented Programming&lt;/title>
        <credithours>3 + 1&lt;/credithours>
        &lt;prerequisites>Fundamentals of Programming&lt;/prerequisites>
    &lt;/course>
&lt;/courses>';
 
$xml = simplexml_load_string($courses_xml);
$json = json_encode($xml, JSON_PRETTY_PRINT);
$array = json_decode($json, true);
 
?>

The output is as follows.

Array
(
    [course] => Array
        (
            [0] => Array
                (
                    [title] => Fundamentals of Programming
                    [credithours] => 3 + 1
                    [prerequisites] => None
                )
 
            [1] => Array
                (
                    [title] => Object Oriented Programming
                    [credithours] => 3 + 1
                    [prerequisites] => Fundamentals of Programming
                )
 
        )
 
)

Voila! Using JSON as an intermediate data format makes it alot more easier.

Note I: XML to Object PHP using json_decode

Hopefully, by now you have picked up the hint above for converting XML to Object. All we need is to drop the boolean argument in the json_decode function.

$object = json_decode($json);

The function returns an object as.

stdClass Object
(
    [course] => Array
        (
            [0] => stdClass Object
                (
                    [title] => Fundamentals of Programming
                    [credithours] => 3 + 1
                    [prerequisites] => None
                )
 
            [1] => stdClass Object
                (
                    [title] => Object Oriented Programming
                    [credithours] => 3 + 1
                    [prerequisites] => Fundamentals of Programming
                )
 
        )
 
)

Note II: PHP XML to Array with attributes

Let’s see what happens when we introduce attributes to XML tag. Here’s how it looks after.

'&lt;courses>
    &lt;course id="C-001">
        &lt;title>Fundamentals of Programming&lt;/title>
        &lt;credithours>3 + 1&lt;/credithours>
        &lt;prerequisites>None&lt;/prerequisites>
    &lt;/course>
    &lt;course id="C-002">
        &lt;title>Object Oriented Programming</title>
        &lt;credithours>3 + 1&lt;/credithours>
        &lt;prerequisites>Fundamentals of Programming&lt;/prerequisites>
    &lt;/course>
&lt;/courses>'


Luckily, we don’t need any extra hardwork. The encoder makes “@attributes” node for every tag that includes attributes.

Array
(
    [course] => Array
        (
            [0] => Array
                (
                    [@attributes] => Array
                        (
                            [id] => C-002
                        )
 
                    [title] => Fundamentals of Programming
                    [credithours] => 3 + 1
                    [prerequisites] => None
                )
 
            [1] => Array
                (
                    [title] => Object Oriented Programming
                    [credithours] => 3 + 1
                    [prerequisites] => Fundamentals of Programming
                )
 
        )
 
)

Option 2: Convert XML to Array in PHP using a Third Party Package

We’ll be using mtownsend/xml-to-array to convert a valid XML file to array PHP. First, we need it to install it via Composer.

composer require mtownsend/xml-to-array

The package exports an XmlToArray class with a static function convert. Here’s how to convert XML to array in PHP using this package.

<?php
require __DIR__ . '/vendor/autoload.php';
 
$courses_xml =
'&lt;courses>
    &lt;course id="C-001">
        &lt;title>Fundamentals of Programming&lt;/title>
        &lt;credithours>3 + 1&lt;/credithours>
        &lt;prerequisites>None&lt;/prerequisites>
    &lt;/course>
    &lt;course id="C-002">
        &lt;title>Object Oriented Programming&lt;/title>
        &lt;credithours>3 + 1&lt;/credithours>
        &lt;prerequisites>Fundamentals of Programming&lt;/prerequisites>
    &lt;/course>
&lt;/courses>';
 
$array = Mtownsend\XmlToArray\XmlToArray::convert($courses_xml);
?>

Works well! Here’s the output. Observe that it caters to the attributes the same way as the last option.

Array
(
    [course] => Array
        (
            [0] => Array
                (
                    [title] => Fundamentals of Programming
                    [credithours] => 3 + 1
                    [prerequisites] => None
                    [@attributes] => Array
                        (
                            [id] => C-001
                        )
 
                )
 
            [1] => Array
                (
                    [title] => Object Oriented Programming
                    [credithours] => 3 + 1
                    [prerequisites] => Fundamentals of Programming
                    [@attributes] => Array
                        (
                            [id] => C-002
                        )
 
                )
 
        )
 
)

Perfect! I guess we are good to go. If you want to read more about this package, follow the link.

Conclusion

Wrap Up

We have seen XML to array or object in PHP. The first option is the extension of XML to JSON with an additional decoding step. The other approach uses a third-party package. Both of these options also pick up the XML attributes and place them in the “@attributes” node.

Functions & Packaged Mentioned

simplexml_load_string: (PHP 5, 7, 8) This is a core PHP function that was first introduced in PHP 5. You should be safe to use this function as there is no concern of deprecation in the near future. It is the standard function to load an XML string into PHP.

json_encode: (PHP 5.2+, 7, 8) You will come across this function anytime you need to create a JSON string. It is commonly used to output your REST APIs. This is also a core function and deprecation is unlikely in the near or distant future.

json_decode: (PHP 5.2+, 7, 8) This function is quite handy in transforming JSON to PHP array or object. It is commonly used in various scenarios where the transformation is necessary. Besides, it is a core function and based on the extensive use over time it seems depreciation is unlikely in the near or distant future.

mtownsend/xml-to-array (PHP 7, 8) This package provides a utility class for XML to array tranformation in PHP. At the time of writing this article, it has 354,783 downloads and 84 stars. Personally, it was easy to use and returned quick results.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

  Was this information helpful?

Can Your Career Use a Boost?

Check out our free PHP developer career guide. We created this guide as a resource to help fellow programmers level up their careers. This is an excellent resource whether you are new to programming or have been a professional for more than 15 years.

Click here to read the guide


Article Categories

Article Tags

© 2022 Confident.Systems