在PHP中使用gzip解压缩大文件 [英] Unpack large files with gzip in PHP
问题描述
我为文件使用了一个简单的解压缩功能(如下所示),因此在进一步处理文件之前,不必手动解压缩文件.
I'm using a simple unzip function (as seen below) for my files so I don't have to unzip files manually before they are processed further.
function uncompress($srcName, $dstName) {
$string = implode("", gzfile($srcName));
$fp = fopen($dstName, "w");
fwrite($fp, $string, strlen($string));
fclose($fp);
}
问题是,如果gzip文件很大(例如50mb),则解压缩将需要大量的ram处理.
The problem is that if the gzip file is large (e.g. 50mb) the unzipping takes a large amount of ram to process.
问题:我可以分块解析gzip压缩的文件,但仍然可以获得正确的结果吗?还是有更好的其他方法来处理提取大型gzip文件的问题(即使还要花几秒钟的时间)?
The question: can I parse a gzipped file in chunks and still get the correct result? Or is there a better other way to handle the issue of extracting large gzip files (even if it takes a few seconds more)?
推荐答案
gzfile()是调用gzopen,gzread和gzclose的便捷方法.
gzfile() is a convenience method that calls gzopen, gzread, and gzclose.
是的,您可以手动执行gzopen并gzread读取文件.
So, yes, you can manually do the gzopen and gzread the file in chunks.
这将以4kB的块解压缩文件:
This will uncompress the file in 4kB chunks:
function uncompress($srcName, $dstName) {
$sfp = gzopen($srcName, "rb");
$fp = fopen($dstName, "w");
while (!gzeof($sfp)) {
$string = gzread($sfp, 4096);
fwrite($fp, $string, strlen($string));
}
gzclose($sfp);
fclose($fp);
}
这篇关于在PHP中使用gzip解压缩大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!