【问题标题】:file_get_contents equivalent for gzipped files与 gzip 文件等效的 file_get_contents
【发布时间】:2023-04-07 16:27:02
【问题描述】:

file_get_contents 等效的函数是什么,它读取使用gzwrite 函数编写的文本文件的全部内容?

【问题讨论】:

    标签: php file gzip


    【解决方案1】:

    使用stream wrappers 会更容易

    file_get_contents('compress.zlib://'.$file);
    

    https://stackoverflow.com/a/8582042/1235815

    【讨论】:

      【解决方案2】:

      显然是 gzread .. 还是你的意思是 file_put_contents

      编辑: 如果您不想有句柄,请使用readgzfile

      【讨论】:

      • 谢谢,但 file_get_contents 将文件路径作为参数,而不是句柄。 gzread 使用资源,而不是路径,所以这不是等价的。
      • readgzfile 输出到标准输出,而不是字符串。但是使用gzread 对我来说效果很好。例如。 $zd = gzopen($fname, "r");$gz = gzread($zd, 100 * 1024 * 1024);gzclose($zd);(我将最大文件大小设置为 100MB;如果不够,请调整。)
      【解决方案3】:

      我尝试了@Sfisioza 的答案,但遇到了一些问题。它还会读取文件两次,一次是非压缩文件,然后是压缩文件。这是一个精简版:

      public function gz_get_contents($path){
          $file = @gzopen($path, 'rb', false);
          if($file) {
              $data = '';
              while (!gzeof($file)) {
                  $data .= gzread($file, 1024);
              }
              gzclose($file);
          }
          return $data;
      }
      

      【讨论】:

        【解决方案4】:

        我根据手册中的 cmets 写了一个我正在寻找的函数:

        /**
         * @param string $path to gzipped file
         * @return string
         */
        public function gz_get_contents($path)
        {
            // gzread needs the uncompressed file size as a second argument
            // this might be done by reading the last bytes of the file
            $handle = fopen($path, "rb");
            fseek($handle, -4, SEEK_END);
            $buf = fread($handle, 4);
            $unpacked = unpack("V", $buf);
            $uncompressedSize = end($unpacked);
            fclose($handle);
        
            // read the gzipped content, specifying the exact length
            $handle = gzopen($path, "rb");
            $contents = gzread($handle, $uncompressedSize);
            gzclose($handle);
        
            return $contents;
        }
        

        【讨论】:

          【解决方案5】:
          file_get_contents("php://filter/zlib.inflate/resource=/path/to/file.gz");
          

          我不确定它会如何处理 gz 文件头。

          【讨论】:

          • 这对我不起作用(PHP 5.5.9,Mint 17);我得到一个 0 字节的文件。
          猜你喜欢
          • 1970-01-01
          • 2012-02-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多