file_get_contents equivalent for gzipped files

2019-04-28 14:29发布

问题:

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

回答1:

This is way easier using stream wrappers

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

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



回答2:

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

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



回答3:

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;
}


回答4:

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:

file_get_contents("php://filter/zlib.inflate/resource=/path/to/file.gz");

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



标签: php file gzip