PHP XML to Array Conversion Example

To convert an XML file to an array in PHP, you can use the SimpleXMLElement class, which is a built-in class for parsing XML data. Here’s an example of how to do it:

Assuming you have an XML file named “data.xml” with the following content:

<?xml version="1.0"?>
<fruits>
    <fruit>
        <name>Apple</name>
        <color>Red</color>
    </fruit>
    <fruit>
        <name>Banana</name>
        <color>Yellow</color>
    </fruit>
</fruits>

You can use the following PHP code to convert the XML file to an array:

<?php
// Load the XML file
$xmlString = file_get_contents('data.xml');
$xml = new SimpleXMLElement($xmlString);

// Convert the XML to an array
$jsonString = json_encode($xml);
$array = json_decode($jsonString, true);

// Output the array
print_r($array);
?>

Output:

Array
(
    [fruit] => Array
        (
            [0] => Array
                (
                    [name] => Apple
                    [color] => Red
                )

            [1] => Array
                (
                    [name] => Banana
                    [color] => Yellow
                )

        )

)

In the example above, we read the XML file using file_get_contents() and then create a SimpleXMLElement object from the XML string. We convert the SimpleXMLElement object to a JSON string using json_encode() and then decode that JSON string to an associative array using json_decode() with the second parameter set to true.

The resulting array contains the data from the XML file, and you can access it like any other PHP array.