我即将阅读大小为200Mb的文本文件,然后在里面编辑内容然后将其保存回来。但我有错误。所以:
另外,哪种文件阅读方法最适合打开&解析大尺寸文件?我的意思是:
答案 0 :(得分:5)
我必须做类似的事情,阅读1GB文件。我想在PHP中保持不变,所以最后我用fread一点一点地读取文件的一部分:
while (!feof($source_file)) {
$buffer = fread($source_file, 1024); // use a buffer of 1024 bytes
$buffer = str_replace($old,$new,$buffer);
fwrite($target_file, $buffer);
}
这样,在任何给定时间,只有一小部分文件保存在内存中。我检查了效率 它很好,大约半分钟的整个文件。
一个小注释 - 如果被替换的字符串位于缓冲区的末尾,则可能无法替换它。为了确保你改变了所有的事件,再次用一个小的偏移来运行脚本:
$buffer = fread($source_file, 512);
fwrite($target_file, $buffer);
while (!feof($source_file)) {
$buffer = fread($source_file, 1024); // use a buffer of 1024 bytes
$buffer = str_replace($old,$new,$buffer);
fwrite($target_file, $buffer);
}
答案 1 :(得分:1)
与现有的答案大致相同,但使用文件指针。
$original = fopen("/tmp/inputfile.txt", "r");
$new = fopen("/tmp/outputfile.txt", "w");
if ($original && $new) {
while (($buffer = fgets($handle)) !== false) {
//do modification on $buffer (which is a single line)
fwrite($new, $buffer);
}
fclose($original);
fclose($new);
}
答案 2 :(得分:0)
我使用以下内容完成类似的任务:
$file = file_get_contents("/path/to/file");
$lines = explode("\n", $file);
$arr = preg_grep("/search_string/", $lines);
// $arr is now a smaller array of things to match
// do whatever here
// write back to file
file_put_contents("/path/to/file", implode("\n", array_merge($arr, $lines)));
答案 3 :(得分:-5)
PHP并非旨在或打算这样做。您可能需要考虑使用Perl,或将文本更改为XML,或将其放入数据库中。
按照您的意图执行此操作意味着整个文件将被加载到内存中。如果你有多个用户做同样的事情,你的内存将会快速耗尽。
对于XML解析,请查看此处XMLReader