问题描述
我要读取一个大小为200Mb的文本文件,然后在其中编辑内容,然后将其保存回去.但是我有错误.所以:
I am about to read a text file sized 200Mb and then edit something inside and then to save it back. But i'm having errors. So:
- 应该在php中修改哪些确切设置?
另外,哪种文件读取方法最适合打开&解析大文件?我的意思是:
Also what file reading method is the best for opening & parsing the Big Sized files? I mean:
- fread吗?
- file_get_contents吗?
推荐答案
我必须做类似的事情,读取1GB的文件.我想一直使用PHP,所以最后我使用 fread 来阅读零件的文件,一点一点地:
I had to do something similar, reading 1GB file. I wanted to stay whithin PHP, so finally I used fread to read parts of the file, bit by bit:
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);
}
这样,在任何给定时间,文件的仅一小部分就会保留在内存中.我检查了效率很好,整个文件大约需要半分钟.
This way only a small part of the file is kept in memory at any given time. I've checked the efficiencyand it's good, about half minute for the whole file.
一个小提示-如果替换的字符串位于缓冲区的末尾,则可能不会被替换.为了确保您已更改所有出现的内容,请再次以较小的偏移量运行脚本:
A small note- if the replaced string is in at the end of the buffer it might not be replaced. to make sure you've change all of the occurrences run the script again with a small offset:
$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);
}
这篇关于用PHP阅读&解析大文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!