首页  >  问答  >  正文

linux - php 解压.gz文件格式的方法。

  1. 现在项目我通过url获取到了.gz的文件

  2. 我要处理解压处理压缩文件的内容

  3. 现在知道一种办法,是php调用linux的系统命令tar去解压,然后处理数据

我想问问有没有处理过的朋友,可以php函数处理的!

第一次接触,求指教!

黄舟黄舟2667 天前921

全部回复(2)我来回复

  • 仅有的幸福

    仅有的幸福2017-06-08 11:03:56

    php原声支持,以下来自SO

    // 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);

    回复
    0
  • 学习ing

    学习ing2017-06-08 11:03:56

    一般php安装都自带tar的扩展包,这是我项目中tar的解压函数,仅供参考

    function get_files_name_in_tar($file) {
        require_once 'Archive/Tar.php';
        $ext = get_file_extension($file);
        $tar_handle = null;
        if ($ext === "bz2") {
            $tar_handle = new Archive_Tar($file, "bz2");
        } else if ($ext === "gz") {
            $tar_handle = new Archive_Tar($file, "gz");
        } else if ($ext === "tar") {
            $tar_handle = new Archive_Tar($file);
        } else {
            return false;
        }    
        if (!$tar_handle) {
            return false;
        }    
        $entry_names = $tar_handle->listContent();
    
        return array_column($entry_names, 'filename');
    }

    另外可参考:PHP tar格式解压的三种方式
    还可以通过linux,在php中调用linux命令tar然后exec执行

    回复
    0
  • 取消回复