<root> <person> <name>John</name> " />

PASSWORD RESET

Your destination for complete Tech news

PHP

How to convert an XML to an array in PHP?

466 0
< 1 min read

To convert an XML string to an array in PHP, you can use the SimpleXML extension, which provides an easy way to parse and manipulate XML data. Here’s an example code snippet:

$xml_string = '<?xml version="1.0" encoding="UTF-8"?>
<root>
    <person>
        <name>John</name>
        <age>30</age>
        <email>[email protected]</email>
    </person>
    <person>
        <name>Jane</name>
        <age>25</age>
        <email>[email protected]</email>
    </person>
</root>';

$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
$array = json_decode($json, true);

print_r($array);

In this example, we’re starting with an XML string. The simplexml_load_string() function is used to create a SimpleXMLElement object from the XML string.

Next, we convert the SimpleXMLElement object to a JSON string using the json_encode() function. This is necessary because PHP arrays cannot directly be converted from a SimpleXMLElement object.

Finally, we convert the JSON string to a PHP associative array using the json_decode() function with the second argument set to true, indicating that we want an associative array rather than an object.

The resulting $array variable will contain the converted array representation of the original XML data. The output of the example code snippet will be:

Array
(
    [person] => Array
        (
            [0] => Array
                (
                    [name] => John
                    [age] => 30
                    [email] => [email protected]
                )

            [1] => Array
                (
                    [name] => Jane
                    [age] => 25
                    [email] => [email protected]
                )

        )

)

This represents an associative array containing the same data as the original XML, with each person represented as an array containing their name, age, and email.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.