我有一个非常大的文本文件,包含超过10000个条目。我需要将数据存储到一个数组中,因为在将所有数据存储到mySQL数据库中之前,我需要检查并验证所有条目。
$file_path = $filename;
$linesArray = file($file_path);
$properties = array();
foreach ($linesArray AS $line) {
if (strlen($line) && $line[0] == '#') {
$pdate = substr($line, 1);
$date = rtrim($pdate);
$formatted = DateTime::createFromFormat('* M d H:i:s T Y',$date);
}
if (false !== ($pos = strpos($line, '='))) {
$prop=array();
$prop[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1));
$lineContArray = explode("=", $line);
$identArray = explode(".", $lineContArray[0]);
$ident = $identArray[0];
$type = $identArray[1];
$value = trim($lineContArray[1]);
$found = 0;
for ($i=0; $i<count($properties); $i++) {
if ($properties[$i]['number'] == $ident) {
$properties[$i][$type]= $value;
$found=1;
break;
}
}
if ($found == 0) {
if (!empty($type)) {
$properties[] = array('number' => $ident, $type => $value);
} else {
$properties[] = array($ident => $value);
}
}
}
}
var_dump($properties);
这对多达3000个条目的文件非常有效,但对于较大的文件,我会得到一个空白页面。
您可以在每次迭代中转储添加到该数组中的元素,而不是在处理完整个文件后转储数组。这样就有了一个输出流:
...
if ($found == 0) {
if (!empty($type)) {
$property = array('number' => $ident, $type => $value);
} else {
$property = array($ident => $value);
}
// dump this line's result and a linebreak:
var_dump($property);
echo '<br>';
$properties[] = $property;
}
}
}
// not needed anymore:
//var_dump($properties);
//
如果输出仍然没有通过,请在代码中添加flush()。
对您的代码的一些评论
当处理具有等号但没有前一个点的行时,代码中的最后一行将产生运行时错误:
$identArray = explode(".", $lineContArray[0]);
$ident = $identArray[0];
$type = $identArray[1];
内部环路(for ($i=0; $i<count($properties); $i++)
)的效率非常低。最好制作一个由$ident
键控的关联数组,其中包含对$properties
数组的引用。这样你的查找就不需要循环了。
我们可以使用fread或fget进行大文件
这将逐行读取
if ($handle = @fopen("inputfile.txt", "r")) {
while (($readLine = fgets($handle, 4096)) !== false) {
echo $readLine;
//create an array according to the text data
}
fclose($handle);
}
供参考:-http://www.php.net/manual/en/function.fread.php