php - Unable to Access @attributes in XML Node -
i trying access 'field' element in 'criteria' node in following xml:
<?xml version="1.0" encoding="utf-8"?> <result> <product> <data> <field>spr_tech1</field> <value>s7</value> <criteria field="xfield_3"> <criteria_list>green</criteria_list> <criteria_list>beige</criteria_list> </criteria> </data> <data> <field>spr_tech1</field> <value>s1</value> <criteria field="xfield_3"> <criteria_list>red</criteria_list> <criteria_list>blue</criteria_list> <criteria_list>yellow</criteria_list> </criteria> </data> <data> <field>spr_tech1</field> <value>s7</value> <criteria field="xfield_3"> <criteria_list>green</criteria_list> </criteria> <criteria field="tech_rt2"> <criteria_list>transistor</criteria_list> </criteria> </data> </product> </result>
the code below results in following error: fatal error: call member function attributes() on non-object
function parsexmlfile($filename) { $xml = file_get_contents($filename); $obj = simplexml_load_string($xml, 'simplexmlelement', libxml_nocdata); $array = json_decode(json_encode($obj), true); // convert array} return $array; } $xform = parsexmlfile('transformations.xml'); foreach ($xform['product']['data'] $data) { echo (string)$data['field'] . '<br>'; echo (string)$data['value'] . '<br>'; foreach($data['criteria']->attributes() $att => $val) { echo $att . ' = ' . $val . '<br>'; } echo $data['criteria']->attributes()->{'field'} . '<br>'; foreach($data['criteria']['criteria_list'] $att => $val) { echo $att . ' = ' . $val . '<br>'; } echo "-----------------------------------<br>"; } print "<pre>"; print_r($xform); print "</pre>";
i've tried couple methods can see in code, neither working me.
any appreciated!
it seems problem when load file. tried file_get_contents()
see below
$xml_content = file_get_contents('path xml file'); $xform = simplexml_load_string($xml_content); foreach ($xform['product']['data'] $data) { echo (string)$data['field'] . '<br>'; echo (string)$data['value'] . '<br>'; foreach($data['criteria']->attributes() $att => $val) { echo $att . ' = ' . $val . '<br>'; } echo $data['criteria']->attributes()->{'field'} . '<br>'; foreach($data['criteria']['criteria_list'] $att => $val) { echo $att . ' = ' . $val . '<br>'; } echo "-----------------------------------<br>"; } print "<pre>"; print_r($xform); print "</pre>";