2009-08-11 48 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

相關問題