0

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" } 
}
2
  • what format you actually want? do print_r() instead of "var_dump()` and check the format Commented Apr 19, 2018 at 4:45
  • @prakashtank I want the first case should be like this ------ array(1){ [0]=>{ ["cid"]=> string(1) "1" ["name"]=> string(4) "Adam" ["age"]=> string(2) "20"} } Commented Apr 19, 2018 at 4:50

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.