AlB*_*ebe 97
这段代码可以解决问题
// Name of the file we're compressing
$file = "test.txt";
// Name of the gz file we're creating
$gzfile = "test.gz";
// Open the gz file (w9 is the highest compression)
$fp = gzopen ($gzfile, 'w9');
// Compress the file
gzwrite ($fp, file_get_contents($file));
// Close the gz file and we're done
gzclose($fp);
Run Code Online (Sandbox Code Playgroud)
Sim*_*ast 87
这里的其他答案在压缩期间将整个文件加载到内存中,这将导致大文件上的"内存不足 "错误.下面的函数在大文件上应该更可靠,因为它以512kb的块读取和写入文件.
/**
* GZIPs a file on disk (appending .gz to the name)
*
* From http://stackoverflow.com/questions/6073397/how-do-you-create-a-gz-file-using-php
* Based on function by Kioob at:
* http://www.php.net/manual/en/function.gzwrite.php#34955
*
* @param string $source Path to file that should be compressed
* @param integer $level GZIP compression level (default: 9)
* @return string New filename (with .gz appended) if success, or false if operation fails
*/
function gzCompressFile($source, $level = 9){
$dest = $source . '.gz';
$mode = 'wb' . $level;
$error = false;
if ($fp_out = gzopen($dest, $mode)) {
if ($fp_in = fopen($source,'rb')) {
while (!feof($fp_in))
gzwrite($fp_out, fread($fp_in, 1024 * 512));
fclose($fp_in);
} else {
$error = true;
}
gzclose($fp_out);
} else {
$error = true;
}
if ($error)
return false;
else
return $dest;
}
Run Code Online (Sandbox Code Playgroud)
Car*_*rós 20
此外,您可以使用php的包装器,压缩包装器.只需对代码进行最小的更改,您就可以在gzip,bzip2或zip之间切换.
$input = "test.txt";
$output = $input.".gz";
file_put_contents("compress.zlib://$output", file_get_contents($input));
Run Code Online (Sandbox Code Playgroud)
更改compress.zlib://到 (看到这个答案约ZIP压缩评论),或者compress.zip://为zip压缩compress.bzip2://以压缩的bzip2.
带gzencode()的简单单线程:
gzencode(file_get_contents($file_name));
Run Code Online (Sandbox Code Playgroud)