2017-06-13 144 views
-1

我正在创建一个将csv文件导入数据库的函数。但是发生了一个错误,我想知道如何解决这个问题。php - 致命错误:允许的内存大小为134217728字节耗尽

Error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

我的功能:

importFile("ingram", "ingram_fees.txt", "ingram_fees"); 

function importFile($company, $fileName, $tableName) { 
    $filePath = "./ftp_imports/".$company."/".$fileName; 
    $file = fopen($filePath, "r"); 
    $firstRowNames = fgetcsv($file); 
    $columnNames = array(); 
    $rows = count($firstRowNames); 
    $i = 0; 
    while ($i < $rows) { 
     array_push($columnNames, toCamelCase($firstRowNames[$i])); 
    } 
    if ($result = $mysqli->query("SHOW TABLES LIKE '".$tableName."'")) { 
     if($result->num_rows !== 1) { 
      $queryCreateTable = "CREAT TABLE $tableName ("; 
      $num = count($columnNames); 
      $i = 0; 
      while ($i < $num) { 
       switch (gettype($columnNames[$i])) { 
        case 'string': 
         $queryCreateTable .= $columnNames[$i] . " VARCHAR(25)"; 
         break; 
        case 'integer': 
         $queryCreateTable .= $columnNames[$i] . " DECIMAL(10,2)"; 
         break; 
        case 'double': 
         $queryCreateTable .= $columnNames[$i] . " DECIMAL(10,2)"; 
         break; 
        case 'NULL': 
         $queryCreateTable .= $columnNames[$i] . " VARCHAR(25)"; 
         break; 
        default: 
         break; 
       } 
       if ($i !== ($num - 1)) { 
        $queryCreateTable .= ","; 
       } else { 
        $queryCreateTable .= ");"; 
       } 
      } 
     } 
    } else {//table already exists 
     $queryDelAll = "TRUNCATE TABLE $tableName"; 
     $db->query($queryDelAll); 

     $queryImport = <<<eof 
      LOAD DATA LOCAL INFILE '$filePath' 
      INTO TABLE $tableName 
      FIELDS TERMINTED BY ',' 
      LINES TERMINATED BY '\n' 
      INGORE 1 LINES 
      ($columnNames) 
      eof; 
      $db->query($queryImport); 
     } 
    } 

这给了,因为它的内存使用量的误差的功能。

function toCamelCase($string, $capitalizeFirstCharacter = false) { 
    $str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string))); 
    if (!$capitalizeFirstCharacter) { 
     $str[0] = strtolower($str[0]); 
    } 
    return $str; 
} 

因为$columnNames阵列只有8个值长,我不知道为什么内存使用率是很高。

有人可以帮我吗?

感谢, 每

+0

..:

$i = 0; while ($i < $rows) { array_push($columnNames, toCamelCase($firstRowNames[$i])); } 

更好“);(例如'256M' for 256 Mb) –

+0

您需要更新php ini memory_limit – fortune

+3

'$ i'永远不会在循环中增加,因此'$ columnNames'无限增长。 – Blackhole

回答

1

有一个无限循环,因为你忘了$递增我。在您的PHP安装的内存限制,或者通过编辑多数民众赞成使用的`php.ini`文件,或通过设置'的ini_set( “memory_limit的”,”

$i = 0; 
while ($i < $rows) { 
    array_push($columnNames, toCamelCase($firstRowNames[$i])); 
    ++$i; 
} 
+0

可能重复愚蠢的错误。感谢帮助 :) – Perra

相关问题