tags:

views:

220

answers:

1

I have a single xml parsing function that I'm trying to call multiple times as I only need to strip a little data out and continue on.

Here is the function:

//Parse Product ID from Product Sides
function getProductSpecs($xml,$type) {

    // Setup arrary
    global $productspecs;
    global $count;
    $count = 0;
    global $type_check;
    $type_check = $type;

    // Parse the XML
    // Create the parser
    if (! ($xmlparser = xml_parser_create()) )
    { 
     die ("Cannot create name list parser");
    }

    // Start tag function
    function first($parser, $name, $attribs) {
     global $trigger;
     if ($name == "PRODUCTSIDEID") {
      $trigger = 1;
     } elseif ($name == "PRODUCTID") {
      $trigger = 1;
     }
    }

    // data handler function
    function xml($parser, $data) {
     global $trigger;
     global $productspecs;
     global $count;
     global $type_check;
     if ($trigger == 1){
      if ($type_check == "sideid") {
       $productspecs[$count]=$data;
       $count = $count + 1;
      } elseif ($type_check == "productid") {
       $productspecs[$count]=$data;
       $count = $count + 1;
      }    
      $trigger = 0;
     }
    }

    // Call the handler functions
    xml_set_element_handler($xmlparser, "first", "");

    // Call the data handler
    xml_set_character_data_handler($xmlparser, "xml");

    // Parse the XML data
    xml_parse($xmlparser,$xml);
    // Clear parser
    xml_parser_free($xmlparser);

    //Return the array
    return $productspecs;
}

My problem arises when this is called:

xml_set_element_handler($xmlparser, "first", "");

I get the redeclare error on:

function first($parser, $name, $attribs) {

The function only appears the one time and I'm assuming the problem occurs on the call but is there a way around this so I don't have to duplicate so much code. I'm going to have to iterate through this multiple times.

Thanks.

+1  A: 

Defining functions inside of functions can lead to this. Each time you run getProductSpecs() it's going to try to declare first() and xml() again, and in PHP, all user functions are declared in a global scope. The best solution is to move your first() function and your xml() function outside of the main getProductSpecs() function.

Another option is to use function_exists() around your function declarations, like this:

if (! function_exists('first')) {
 // Start tag function
    function first($parser, $name, $attribs) {
        global $trigger;
        if ($name == "PRODUCTSIDEID") {
                $trigger = 1;
        } elseif ($name == "PRODUCTID") {
                $trigger = 1;
        }
    }
}
zombat
Thank you for the response. I figured it was something to that effect I just hadn't wrapped my head around it.
techguytom