How to convert xml into array of objects in php?

by aniya.jaskolski , in category: PHP General , 5 months ago

How to convert xml into array of objects in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 4 months ago

@aniya.jaskolski 

You can use the SimpleXMLElement class in PHP to parse an XML file and convert it into an array of objects. Here's an example code snippet that demonstrates how to do this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$xmlString = '<data>
    <item>
        <name>John</name>
        <age>25</age>
    </item>
    <item>
        <name>Jane</name>
        <age>30</age>
    </item>
</data>';

// Load the XML string
$xml = new SimpleXMLElement($xmlString);

// Convert XML into array of objects
$arrayOfObjects = [];
foreach ($xml->children() as $item) {
    $object = new stdClass();
    foreach ($item->children() as $element) {
        $object->{$element->getName()} = (string) $element;
    }
    $arrayOfObjects[] = $object;
}

// Print the array of objects
print_r($arrayOfObjects);


This code will output the following array of objects:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Array
(
    [0] => stdClass Object
        (
            [name] => John
            [age] => 25
        )

    [1] => stdClass Object
        (
            [name] => Jane
            [age] => 30
        )

)