DonDave
DonDave

Reputation: 63

Convert XML file to an array

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" } 
}

Upvotes: 0

Views: 237

Answers (1)

scrowler
scrowler

Reputation: 24435

Here's one option (using simplexml_load_string instead of file):

function getCustomersFromXml($xml, $key = 'customer')
{
    $data = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    $out = [];
    foreach ($data->$key as $item) {
        $out[] = (array) $item;
    }
    return $out;
}

So you load the XML data, loop the customers object and push each customer object cast as an array into your output.

https://eval.in/990764

Upvotes: 1

Related Questions