【发布时间】:2011-01-14 18:10:47
【问题描述】:
我有一个 209MB 的 .txt 文件,它包含大约 95,000 行,每周会自动推送到我的服务器一次,以更新我网站上的一些内容。问题是我无法分配足够的内存来处理这么大的文件,所以我想将大文件分成小文件,每个文件 5,000 行。
在文件被分解成更小的部分之前,我根本无法使用 file(),所以我一直在使用 SplFileObject。但我没有得到它。这是我想要完成的一些伪代码:
read the file contents
while there are still lines left to be read in the file
create a new file
write the next 5000 lines to this file
close this file
for each file created
run mysql update queries with the new content
delete all of the files that were created
文件为 csv 格式。
编辑:这是逐行读取文件的解决方案,给出以下答案:
function getLine($number) {
global $handle, $index;
$offset = $index[$number];
fseek($handle, $offset);
return explode("|",fgets($handle));
}
$handle = @fopen("content.txt", "r");
while (false !== ($line = fgets($handle))) {
$index[] = ftell($handle);
}
print_r(getLine(18437));
fclose($handle);
【问题讨论】:
-
您要进行什么样的处理?通过
fopen和fgets读取应该可以正常工作,除非您尝试将其全部存储在一个数组中。 -
第二个
fgets。这样您就可以逐行读取,而无需将整个文件加载到内存中。 -
我可以使用 fgets 按字节输出文件。我可以使用 fgets 按行号获取文件内容吗?
-
另外,您可以使用 unix
split命令来拆分文件。可能会快一点。但正如@mfonda 所说,您没有任何理由需要这样做。
标签: php file memory-management pseudocode