[UPHPU] parsing XML
Wade Preston Shearer
wadeshearer.lists at me.com
Thu Feb 25 16:10:18 MST 2010
I am working with GoEmerchant's XML Gateway. The responses are returned as XML. A simple way to convert this into usable information is using simplexml_load_string() (part of the SimpleXML extension). This isn't working for me however since it returns each node with a numbered index and since GoEmerchant's responses are different depending on the type of transaction and whether it is successful or not, I cannot address the nodes by their order (or index) or might grab the wrong one.
So, I used the XML Parser extension and came up with this:
$p = xml_parser_create();
xml_parse_into_struct($p, $resp, $vals, $index);
xml_parser_free($p);
// extract the fields
foreach($index['FIELD'] as $field) {
$fields[$vals[$field]['attributes']['KEY']] = $vals[$field]['value'];
}
…where $resp is the XML passed in and $fields are the nodes I want.
Here is an example of the XML:
<?xml version="1.0" encoding="utf-8"?>
<RESPONSE>
<FIELDS>
<FIELD KEY="status">1</FIELD>
<FIELD KEY="auth_code">DEMO92</FIELD>
<FIELD KEY="auth_response">APPROVED</FIELD>
<FIELD KEY="avs_code">X</FIELD>
<FIELD KEY="cvv2_code"> </FIELD>
<FIELD KEY="order_id">2143317674</FIELD>
<FIELD KEY="reference_number">29624</FIELD>
<FIELD KEY="error" />
</FIELDS>
</RESPONSE>
Here is the $fields array that I produce:
Array
(
[status] => 1
[auth_code] => DEMO92
[auth_response] => APPROVED
[avs_code] => X
[cvv2_code] =>
[order_id] => 2143317674
[reference_number] => 29624
[error] =>
)
Any better ways to do this?
More information about the UPHPU
mailing list