11

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

4

5 回答 5

23

使用流包装器更容易

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

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

于 2016-02-05T12:43:38.940 回答
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.

于 2013-08-13T10:38:03.277 回答
2

我尝试了@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;
}
于 2015-03-30T16:04:40.183 回答
1

根据手册中的评论,我编写了一个我正在寻找的函数:

/**
 * @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;
}
于 2013-08-13T11:34:42.850 回答
0
file_get_contents("php://filter/zlib.inflate/resource=/path/to/file.gz");

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

于 2013-08-13T11:16:42.337 回答