tags:

views:

47

answers:

2

Hi there,

I'm parsing a posted encrypted and posted XML file sent to my site from another server.

Currently the XML(decrypted) sorta looks like so:

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<transactions>
<transaction>
 <id>407145</id>
 <store_id>4067</store_id>
 <custom_fields>
  <custom_field>
   <custom_field_name>affiliateID</custom_field_name>
   <custom_field_value>25</custom_field_value>
  </custom_field>
     </custom_fields>
</transaction>
</transactions>

And the parser looks like so:

$XMLData = rc4crypt::decrypt($key, urldecode($_POST["XMLData"]));
$data = new XMLParser($FoxyData);   // Parse that XML.
$data->Parse();

// go through each of the nodes
foreach ($data->document->transactions[0]->transaction as $tx) {

    $id = $tx->id[0]->tagData;
    $store_id = $tx->id[0]->tagData;

    // get the affiliateID
    foreach ($tx->custom_fields[0]->custom_field as $field) {
    $affiliateID = $field->custom_field_value[0]->tagData;
}



}

The above works unless the XML being sent to our server is missing the custom_fields nodes. Then it throws up an error "Undefined property: XMLTag::$custom_field".

Since I'm a hack, I thought something like the following would work, but it doesn't:

if($tx->custom_fields[0]->custom_field) {

   foreach ($tx->custom_fields[0]->custom_field as $field) {
    $affiliateID = $field->custom_field_value[0]->tagData;
}

}

That seems logical to me - but what is wrong with my logic? How can I tell my script to not do the foreach if that node doesn't exist in the xml?

+2  A: 

You should check the existence of $tx->custom_fields and $tx->custom_fields[0] first and then use it further.

+1  A: 

I think isset() is probably what you're looking for:

if (isset($tx->custom_fields[0]->custom_field)) {
    foreach ($tx->custom_fields[0]->custom_field as $field) {
        $affiliateID = $field->custom_field_value[0]->tagData;
    }
}

Note that there's no need to check $tx->custom_fields, then $tx->custom_fields[0], separately, using isset() on the deepest level will return false (as opposed to causing an error) even if $tx->custom_fields does not exist.

Tim Sylvester