我一直在尝试将 USDA 营养数据从ascii 版本的数据加载到 mysql 数据库中。我使用了这里的脚本,除了大小约为 34MB 的 NUT_DATA.txt 文件外,其他所有内容都进来了。使用该函数使用 php 脚本正确加载文件(因此内存限制不应该成为问题,无论如何它们都设置为 128M)file_get_contents
。但是,当它到达该preg_split('#\n#', $file)
行时,脚本将结束而没有进一步的注释。如果我将文件分成更小的部分,它运行良好。为什么它不适用于完整文件?我将 memory_limit 设置为 128M,upload_max_filesize 设置为 128M。整个文件似乎已被读入,只是preg_split
似乎有问题。
我有什么明显的遗漏吗?
谢谢!
这是我一直在测试的php代码:
<?php
// from http://drupal.org/node/107806
//$dbh=mysql_connect(/*db info*/);
//mysql_select_db(/*db info*/);
try
{
$dbh = new PDO('mysql:host=127.0.0.1;dbname=XXXXXXX', 'XXXXXXX', 'XXXXXXX');
echo "PDO access worked! <br />";
} catch (PDOException $e)
{
echo "PDO error: " . $e->getMessage() . "<br />";
die();
}
//List of SR20 filenames with associated field counts.
$filenames = array(//"DERIV_CD" => 2,
// "FD_GROUP" => 2,
// "NUTR_DEF" => 6,
// "SRC_CD" => 2,
// "WEIGHT" => 7,
// "FOOTNOTE" => 5,
// "DATA_SRC" => 9,
// "DATSRCLN" => 3,
// "FOOD_DES" => 14,
"NUT_DATA" => 17
// "NUT_DATA2" => 17,
// "NUT_DATA_test" => 17
);
foreach($filenames as $filename => $count) {
echo "inside foreach: $filename ";
$file = file_get_contents($filename.'.txt');
echo " read in the file, length = " . strlen($file) . "<br />";
$lines = preg_split('#\n#', $file);
echo "made it past preg_split <br />";
// print_r($lines);
echo " lines = " . count($lines). "<br />";
for($i=0;$i<count($lines);++$i) {
$line = $lines[$i];
// echo "Inside for loop, line = '" . $line . "'<br />";
//Some text fields are split over several lines. Concatenate them.
while(substr_count($line, '^') < $count-1 || (substr_count($line, '~')%2) == 1) {
++$i;
if($i>=count($lines)) { break; }
$line .= '<br />'.$lines[$i];
}
$fields = trim($line);
if(strlen($fields) == 0) continue;
$fields = str_replace(array("'", '~', '^'), array("''", "'", ','), $fields);
$sql = "INSERT INTO `$filename` VALUES($fields);";
//Insert zeroes for unfilled values.
$sql = str_replace(array(',,', ',)'), array(',0,', ',0)'), $sql);
$sql = str_replace(array(',,', ',)'), array(',0,', ',0)'), $sql);
$sql = str_replace(array(',,', ',)'), array(',0,', ',0)'), $sql);
//Some single-char fields aren't quoted.
$sql = preg_replace('#,([A-Z])\);$#', ",'$1');", $sql);
// comment out the database interface until things are working
/* $stmt = $dbh->prepare($sql);
if(!$stmt->execute())
{
echo $sql;
}
*/
}
}
echo "done";
?>