2009-08-11 49 views
0

我有一个xml解析函数,我试图多次调用,因为我只需要取出一些数据并继续。当重复使用xml解析代码时出现“致命错误:无法重新声明”

下面是函数:

//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; 
} 

我的问题出现时,这就是所谓的:

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

我上重新声明错误:

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

该功能仅出现在有一次,我假设问题出现在通话中,但有没有办法解决这个问题,所以我不必杜激发这么多代码。我将不得不迭代多次。

谢谢。

回答

1

在函数内部定义函数可能导致这种情况。每次运行getProductSpecs()它都会尝试再次声明first()xml(),并且在PHP中,所有用户函数都是declared in a global scope。最好的解决方案是将first()函数和xml()函数移到主函数getProductSpecs()之外。

另一种选择是使用在你的函数声明,就像这样:

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

谢谢你的答复。我觉得这是我刚才没有把头绕在它身上的原因。 – techguytom 2009-08-12 14:46:34

相关问题