I try to convert XML file to an array in PHP. However, when reading the first array, it is not in form of key and value array.
Is there any way to convert the first data in form of Key and Value? Thanks in advance.
readXML.php
function convertXMLFileToArray()
{
$xml_file = 'customers.xml';
$array_name = 'customer';
//Check whether the file exist
if(file_exists($xml_file)){
//Read the data from xml file
$dt = simplexml_load_file($xml_file,null,LIBXML_NOCDATA);
$json = json_encode($dt);
$outer_array = json_decode($json,TRUE);
//Remove outer array
$array = $outer_array[$array_name];
}
else{
$array = null;
}
var_dump($array);
return $array;
}
Case1
customers.xml
<customers>
<customer>
<cid>1</cid>
<name>Adam</name>
<age>20</age>
</customer>
</customers>
Output
array(3) { ["cid"]=> string(1) "1" ["name"]=> string(4) "Adam" ["age"]=> string(2) "20"}
Case2
customers.xml
<customers>
<customer>
<cid>1</cid>
<name>Adam</name>
<age>20</age>
</customer>
<customer>
<cid>2</cid>
<name>David</name>
<age>23</age>
</customer>
</customers>
Output
array(2) {
[0]=> array(3) { ["cid"]=> string(1) "1" ["name"]=> string(4) "Adam"
["age"]=> string(2) "20" }
[1]=> array(3) { ["cid"]=> string(1) "2" ["name"]=> string(4) "David"
["age"]=> string(2) "23" }
}