简体   繁体   中英

How to parse XML using php simplexml_load_file()?

I have the following XML in file:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<conjunctiva>
    <od>
        <conjnctivalchlais examname="Conjunctival Chalasis">
            <negative elem_name="elem_ConjnctivalOd_neg">ASDFGH</negative>
            <positive elem_name="elem_ConjnctivalOd_Pos"/>
            <pos_4 elem_name="elem_ConjnctivalOd_pos4"/>
            <pos_3 elem_name="elem_ConjnctivalOd_pos3"/>
            <pos_2 elem_name="elem_ConjnctivalOd_pos2"/>
            <pos_1 elem_name="elem_ConjnctivalOd_pos1"/>
            <t elem_name="elem_ConjnctivalOd_T"/>
        </conjnctivalchlais>
    </od>
</conjunctiva>

I am using following code to parse xml:

$csvFileName = "con2.xml";
    $conjunctiva = simplexml_load_file($csvFileName);
    foreach($conjunctiva->od as $od){
        if(gettype($od) == "object"){
            $keys = get_object_vars($od);
            $keys2 = array_keys($keys);
        for($i = 0;$i < sizeof($keys2);$i++){
            if(gettype($keys[$keys2[$i]]) == "object"){
                $keys3 = get_object_vars($keys[$keys2[$i]]);
                $keys4 = array_keys($keys3);
                for($j = 0;$j < sizeof($keys4);$j++){
                    if(gettype($keys3[$keys4[$j]]) == "object"){
                    }else if(gettype($keys3[$keys4[$j]]) == "string"){
                    }else if(gettype($keys3[$keys4[$j]]) == "array"){
                    }
                }
            }
        }
    }
}

I want to put XML in array with attribute value as key and node value as value. But it is not working.

 $xml = simplexml_load_file('con2.xml');

 $xmlArray = json_decode(json_encode((array)$xml), TRUE);

 //this should give you the proper array with key=>value pair
 print_r($xmlArray); 

if you want to access the attributes from the SImpleXml Object, use $xml->node and if your nodes contain hiphens like node-name then use it like this $node->{node-name} ,

Edit:

now the $xmlArray should give you proper Array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM