0

I have some XML that looks like this

$xml_str = '<RESPONSE>
    <FIELDS>
    <FIELD KEY="A">1</FIELD>
    <FIELD KEY="B">2</FIELD>
    <FIELD KEY="C">3</FIELD>
    <FIELD KEY="D">4</FIELD>
    </FIELDS>
    </RESPONSE>';

There is only ever going to be 1 "FIELDS" in the response. Is there a easy way I can put the "FIELD" elements in a array with the keys being the "KEY" and the value being the element value?

I could do this

$xml_data = simplexml_load_string($xml_str);
foreach ($xml_data->FIELDS->FIELD as $field) {
    foreach ($field->attributes() as $a => $b) {
        $array[$b] = $field[0];
    }
}

But I'm wondering if there is a better way?

TIA

Analog
  • 261
  • 5
  • 16
  • 2
    That's the proper way. But if you can guarantee the structure of the XML will never change, then you COULD use a regex to extract the attributes all at once... but then you'd be using regexes on XML, which tends to produce loud screams on this site: http://stackoverflow.com/a/1732454/118068 – Marc B May 19 '12 at 19:44
  • Thanks, that helps. Do you by chance know if there is a way I can access a specific key and value directly then? (for example, even though I know this won't work - "print $xml_data->FIELDS->FIELD->attributes("C");" which would return 3).? – Analog May 19 '12 at 19:56
  • Never use regex to parse XML! SimpleXML like you are using is definitely the best way. – None May 19 '12 at 22:56

0 Answers0