file_get_contents equivalent for gzipped files

2019-04-28 14:22发布

What would be equivalent function to file_get_contents, which reads the whole content of a text file written using gzwrite function?

标签: php file gzip
5条回答
来,给爷笑一个
2楼-- · 2019-04-28 14:30
file_get_contents("php://filter/zlib.inflate/resource=/path/to/file.gz");

I'm not sure how it would handle gz file header.

查看更多
男人必须洒脱
3楼-- · 2019-04-28 14:37

This is way easier using stream wrappers

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

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

查看更多
够拽才男人
4楼-- · 2019-04-28 14:37

I tried @Sfisioza's answer, but I had some problems with it. It also reads the file twice, once and non-compresses and then again as compressed. Here is a condensed version:

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;
}
查看更多
一夜七次
5楼-- · 2019-04-28 14:41

It would obviously be gzread .. or do you mean file_put_contents ?

Edit: If you don't want to have a handle, use readgzfile.

查看更多
别忘想泡老子
6楼-- · 2019-04-28 14:41

I wrote a function I was looking for, based on the comments in the manual:

/**
 * @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;
}
查看更多
登录 后发表回答