How to parse xml data to array using php?

by lindsey.homenick , in category: PHP General , 9 months ago

How to parse xml data to array using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 9 months ago

@lindsey.homenick 

To parse XML data into an array using PHP, you can use the simplexml_load_string or simplexml_load_file functions provided by PHP's SimpleXML extension. Here's how you can do it:

  1. Load XML data from a string:
1
2
3
4
5
6
7
$xmlString = '<?xml version="1.0" encoding="UTF-8"?>
<root>
    <element>Value 1</element>
    <element>Value 2</element>
</root>';

$xml = simplexml_load_string($xmlString);


Or load XML data from a file:

1
2
$xmlFile = 'path/to/file.xml';
$xml = simplexml_load_file($xmlFile);


  1. Convert the XML into an array. To convert the XML object into a PHP array, you can use the json_encode function to encode the XML object as JSON, and then use json_decode to decode the JSON back into an array:
1
2
$json = json_encode($xml);
$array = json_decode($json, true);


Now, the XML data from the XML string or file has been converted into a PHP array stored in the $array variable. You can access the elements of the array as per your requirement.


Note: The resulting array might have some differences depending on the XML structure, such as elements with the same name becoming sequential numeric keys. You may need to handle these differences accordingly.