读取文件 PHP 使用太多内存
Reading file PHP using too much memory
因此,我正在尝试解析一个包含 24MB 和 314134 行的文本文件。问题是,我觉得我的脚本使用了太多内存。
这是代码:
if(file_exists($filePath)) {
$data = file_get_contents($filePath);
$lines = explode("\n", $data);
foreach ($lines as $line) {
//Split the line.
$spllitedLine = explode(';', utf8_encode($line));
//Get the fields by their index.
$localidade = !empty($spllitedLine[3]) ? $spllitedLine[3] : '';
$codigo_postal = $spllitedLine[14] . '-' . $spllitedLine[15];
$morada = (!empty($spllitedLine[5]) ? $spllitedLine[5] : ' ') . ' ' .
(!empty($spllitedLine[6]) ? $spllitedLine[6] : ' ') . ' ' .
(!empty($spllitedLine[7]) ? $spllitedLine[7] : ' ') . ' ' .
(!empty($spllitedLine[8]) ? $spllitedLine[8] : ' ') . ' ' .
(!empty($spllitedLine[9]) ? $spllitedLine[9] : '');
//Create a new CTT location and save it to the Database.
$location = new CttLocations();
$location->address = preg_replace('/\s\s+/', ' ', $morada);
$location->location = $localidade;
$location->zipcode = $codigo_postal;
$location->save(false);
//Unset the variables to free space.
unset($location);
unset($line);
unset($morada);
}
}
这当前使用了 153MB 的内存,甚至还不到文件的一半。我读过使用 fopen()
fgets()
和 fclose()
这是一个更好的解决方案,但我使用这些方法使用的内存量大致相同。我究竟做错了什么?我想通过取消设置变量我会释放一些急需的 space。我认为 150MB 对于这样的操作来说太多了。有什么想法吗?
这个:
$data = file_get_contents($filePath);
对于大文件来说太重了。
这是逐行读取文件的方式:
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
}
fclose($handle);
} else {
// error opening the file.
}
因此,我正在尝试解析一个包含 24MB 和 314134 行的文本文件。问题是,我觉得我的脚本使用了太多内存。
这是代码:
if(file_exists($filePath)) {
$data = file_get_contents($filePath);
$lines = explode("\n", $data);
foreach ($lines as $line) {
//Split the line.
$spllitedLine = explode(';', utf8_encode($line));
//Get the fields by their index.
$localidade = !empty($spllitedLine[3]) ? $spllitedLine[3] : '';
$codigo_postal = $spllitedLine[14] . '-' . $spllitedLine[15];
$morada = (!empty($spllitedLine[5]) ? $spllitedLine[5] : ' ') . ' ' .
(!empty($spllitedLine[6]) ? $spllitedLine[6] : ' ') . ' ' .
(!empty($spllitedLine[7]) ? $spllitedLine[7] : ' ') . ' ' .
(!empty($spllitedLine[8]) ? $spllitedLine[8] : ' ') . ' ' .
(!empty($spllitedLine[9]) ? $spllitedLine[9] : '');
//Create a new CTT location and save it to the Database.
$location = new CttLocations();
$location->address = preg_replace('/\s\s+/', ' ', $morada);
$location->location = $localidade;
$location->zipcode = $codigo_postal;
$location->save(false);
//Unset the variables to free space.
unset($location);
unset($line);
unset($morada);
}
}
这当前使用了 153MB 的内存,甚至还不到文件的一半。我读过使用 fopen()
fgets()
和 fclose()
这是一个更好的解决方案,但我使用这些方法使用的内存量大致相同。我究竟做错了什么?我想通过取消设置变量我会释放一些急需的 space。我认为 150MB 对于这样的操作来说太多了。有什么想法吗?
这个:
$data = file_get_contents($filePath);
对于大文件来说太重了。
这是逐行读取文件的方式:
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
}
fclose($handle);
} else {
// error opening the file.
}