How to parse xml data to array using php?

by arnoldo.moen , in category: PHP General , 2 months ago

How to parse xml data to array using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 2 months ago

@arnoldo.moen 

To parse XML data to an array using PHP, you can use the SimpleXMLElement class to parse the XML data and convert it to an array. Here is a simple example:

1
2
3
4
5
6
7
$xmlString = '<data><item name="John" age="30"/><item name="Jane" age="25"/></data>';

$xml = new SimpleXMLElement($xmlString);

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

print_r($array);


In this example, the XML data is stored in a string variable $xmlString. We then create a new instance of SimpleXMLElement using this XML string. We then use json_encode and json_decode functions to convert the object to an associative array.


After running this code, the array variable will contain the parsed XML data in array format.


You can also access specific elements or attributes of the XML data by using the following syntax:

1
2
3
4
5
// Accessing attributes of an element
echo $array['item'][0]['@attributes']['name']; // Output: John

// Accessing elements
echo $array['item'][1]['@attributes']['age']; // Output: 25


This is a simple way to parse XML data to an array using PHP.