搜索文件中的内容并使用PHP更改内容的最佳(最有效)方法是什么?
|
参见英文答案 >
PHP what is the best way to write data to middle of file without rewriting file3个
目前,我处理这个的方法是将整个文件读入一个字符串变量,操作该字符串,然后将整个文件写回文件,完全替换整个文件(通过fopen(filepath,“wb”)和fwrite( )),但这感觉效率低下.有没有更好的办法? 更新:完成我的功能后,我有时间对其进行基准测试.我使用了1GB的大文件进行测试,但结果令人不满意:|是的,内存峰值分配明显更小: >标准解决方案:1,86 GB 但与以下解决方案相比,只有轻微的性能提升: ini_set('memory_limit',-1);
file_put_contents(
'test.txt',str_replace('the','teh',file_get_contents('test.txt'))
);
上面的脚本花了大约16秒,自定义解决方案花了大约13秒. 简历:大型文件的客户解决方案速度稍快,内存消耗更少(!!!). 此外,如果要在Web服务器环境中运行此选项,则自定义解决方案会更好,因为许多并发脚本可能会占用系统的整个可用内存. 原答案: 唯一要记住的是,以符合文件系统块大小的块读取文件,并将内容或修改后的内容写回临时文件.完成处理后,使用rename()覆盖原始文件. 这会降低内存峰值,如果文件非常大,应该会明显加快. 注意:在Linux系统上,您可以使用以下命令获取文件系统块大小: sudo dumpe2fs /dev/yourdev | grep 'Block size' 我得到了4096 功能如下: function freplace($search,$replace,$filename,$buffersize = 4096) {
$fd1 = fopen($filename,'r');
if(!is_resource($fd1)) {
die('error opening file');
}
// the tempfile can be anywhere but on the same partition as the original
$tmpfile = tempnam('.',uniqid());
$fd2 = fopen($tmpfile,'w+');
// we store len(search) -1 chars from the end of the buffer on each loop
// this is the maximum chars of the search string that can be on the
// border between two buffers
$tmp = '';
while(!feof($fd1)) {
$buffer = fread($fd1,$buffersize);
// prepend the rest from last one
$buffer = $tmp . $buffer;
// replace
$buffer = str_replace($search,$buffer);
// store len(search) - 1 chars from the end of the buffer
$tmp = substr($buffer,-1 * (strlen($search)) + 1);
// write processed buffer (minus rest)
fwrite($fd2,$buffer,strlen($buffer) - strlen($tmp));
};
if(!empty($tmp)) {
fwrite($fd2,$tmp);
}
fclose($fd1);
fclose($fd2);
rename($tmpfile,$filename);
}
像这样称呼它: freplace('foo','bar','test.txt'); (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
