How to parse xml data to array using php?

by arnoldo.moen , in category: PHP General , a year ago

How to parse xml data to array using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , a year 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.

Related Threads:

How to parse xml data to array using php?
How to parse a xml string to array in php?
How to parse or download a large xml file in php?
How to convert xml into array of objects in php?
How convert xml with namespaces to php array?
How to parse html element using php?