如何用PHP解压缩.gz文件?

Sha*_*oon 12 php codeigniter unzip

我正在使用CodeIgniter,我无法弄清楚如何解压缩文件!

Pow*_*ord 44

PHP本身有许多用于处理gzip文件的函数.

如果要创建一个新的未压缩文件,它将是这样的.

注意:这不会检查目标文件是否首先存在,不删除输入文件,还是执行任何错误检查.在生产代码中使用它之前,你真的应该修复它们.

// This input should be from somewhere else, hard-coded in this example
$file_name = 'file.txt.gz';

// Raising this value may increase performance
$buffer_size = 4096; // read 4kb at a time
$out_file_name = str_replace('.gz', '', $file_name);

// Open our files (in binary mode)
$file = gzopen($file_name, 'rb');
$out_file = fopen($out_file_name, 'wb');

// Keep repeating until the end of the input file
while(!gzeof($file)) {
    // Read buffer-size bytes
    // Both fwrite and gzread and binary-safe
    fwrite($out_file, gzread($file, $buffer_size));
}

// Files are done, close files
fclose($out_file);
gzclose($file);
Run Code Online (Sandbox Code Playgroud)

注意:这仅适用于gzip .它不涉及焦油.

  • @RealMan gzip 仅支持单个文件。多个文件需要一个 .tar.gz。我不确定 PHP 是否内置了对 tar 的支持。 (2认同)

Dan*_*ial 9

gzopen 工作量太大了。这更直观:

$zipped = file_get_contents("foo.gz");
$unzipped = gzdecode($zipped);
Run Code Online (Sandbox Code Playgroud)

当服务器也吐出 gzipped 数据时,它也适用于 http 页面。


par*_*2eu 6

如果您有权访问 system():

system("gunzip file.sql.gz");
Run Code Online (Sandbox Code Playgroud)


Sar*_*raz 1

下载解压库 并包含autoloadunzip

$this->load->library('unzip');
Run Code Online (Sandbox Code Playgroud)