How to parse a xml string to array in php?

by raven_corwin , in category: PHP General , 3 months ago

How to parse a xml string to array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 3 months ago

@raven_corwin 

To parse an XML string into an array in PHP, you can use the SimpleXMLElement class. Here's an example:

1
2
3
4
5
6
7
8
$xmlString = '<root><item><name>Item 1</name><price>10</price></item><item><name>Item 2</name><price>15</price></item></root>';

$xml = new SimpleXMLElement($xmlString);

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

print_r($array);


This code will convert the XML string into a SimpleXMLElement object using the SimpleXMLElement constructor. Then, we convert the SimpleXMLElement object into a JSON string using json_encode() and finally parse the JSON string into an associative array using json_decode() with the true parameter.


The output will be an array representation of the XML structure:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Array
(
    [item] => Array
        (
            [0] => Array
                (
                    [name] => Item 1
                    [price] => 10
                )

            [1] => Array
                (
                    [name] => Item 2
                    [price] => 15
                )

        )

)