2010-06-13 56 views
0

我从USDA's网站获得这个大的(和奇怪格式的txt文件)。这是NUT_DATA.txt文件。将大分隔文件导入到MySQL表

但问题是,它几乎是27MB!我成功导入了其他一些较小的文件,但我的方法是使用file_get_contents,这有助于在我试图阻止27+ MB RAM时抛出错误。

那么如何将这个庞大的文件导入到我的MySQL数据库中而不会遇到超时和内存问题?我试过每次从文件中获得一行,但是这会遇到超时问题。

使用PHP 5.2.0。

这里是旧脚本(DB中的字段都只是数字,因为我想不出什么数字表示什么营养,我发现这个数据非常糟糕的文档很抱歉的代码的丑陋。):

<? 

    $file = "NUT_DATA.txt"; 

    $data = split("\n", file_get_contents($file)); // split each line 

    $link = mysql_connect("localhost", "username", "password"); 
    mysql_select_db("database", $link); 

    for($i = 0, $e = sizeof($data); $i < $e; $i++) 
    { 
     $sql = "INSERT INTO `USDA` (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17) VALUES("; 
     $row = split("\^", trim($data[$i])); // split each line by carrot 
     for ($j = 0, $k = sizeof($row); $j < $k; $j++) { 
      $val = trim($row[$j], '~'); 
      $val = (empty($val)) ? 0 : $val; 
      $sql .= ((empty($val)) ? 0 : $val) . ','; // this gets rid of those tildas and replaces empty strings with 0s 
     } 
     $sql = rtrim($sql, ',') . ");"; 
     mysql_query($sql) or die(mysql_error()); // query the db 
    } 

    echo "Finished inserting data into database.\n"; 

    mysql_close($link); 

?> 
+0

我不知道PHP ,但我认为如果你可以读取几行文字,那么它可能会更好,然后将它们一次插入到数据库中,然后读取下一行文件直到EOF ... – Sunny 2010-06-13 02:23:37

+0

执行此操作的最佳方法是使用LOA D DATA(参见http://dev.mysql.com/doc/refman/5.1/en/load-data.html)当然这不是PHP,但它也不需要几个小时来加载它。 – 2010-06-13 02:48:44

+0

感谢大家,但它是共享主机,我没有完全访问MySQL,也没有任何其他脚本语言,除了PHP。 – Tom 2010-06-13 02:54:16

回答

2

如果你必须使用PHP,你可以使用fopenfgets

<? 

$file = "NUT_DATA.txt"; 
$fh = @fopen($file, "r"); // open the file for reading 
$link = mysql_connect("localhost", "username", "password"); 
mysql_select_db("database", $link); 

while(!feof($fh)) 
{ 
    $data = fgets($fh, 4096);  // read line from file 

    $sql = "INSERT INTO `USDA` (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17) VALUES("; 
    $row = split("\^", trim($data)); // split each line by carrot 
    for ($j = 0, $k = sizeof($row); $j < $k; $j++) { 
     $val = trim($row[$j], '~'); 
     $val = (empty($val)) ? 0 : $val; 
     $sql .= ((empty($val)) ? 0 : $val) . ','; // this gets rid of those tildas and replaces empty strings with 0s 
    } 
    $sql = rtrim($sql, ',') . ");"; 
    mysql_query($sql) or die(mysql_error()); // query the db 
} 

echo "Finished inserting data into database.\n"; 

fclose($fh); 

mysql_close($link); 

?> 

退房获取更多信息与fgets documentation逐行读取文件中的行

+0

使用这个,set_time_limit,并耐心等待,我设法将整个文件放到数据库中。现在我只需要弄清楚这些数据是什么:) – Tom 2010-06-13 03:08:46

0

可以增加内存的每个脚本可以通过设置在php.ini这个值使用量:

memory_limit = 64M 

说了:你使用PHP?其他脚本语言(如python)可能更适合这类任务。

+0

对于像这样的任务,PHP很好! – mmattax 2010-06-13 02:18:26