11

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

Sfisioza
  • 3,830
  • 6
  • 42
  • 57

6 Answers6

23

This is way easier using stream wrappers

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

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

Community
  • 1
  • 1
Paul Phillips
  • 1,480
  • 1
  • 15
  • 23
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.

tobspr
  • 8,200
  • 5
  • 33
  • 46
  • thanks, but file_get_contents takes as an argument the file path, not the handle. gzread uses resource, not paths, so this is not the equivalent. – Sfisioza Aug 13 '13 at 11:08
  • 1
    `readgzfile` outputs to stdout, not to a string. But using `gzread` worked well for me. E.g. `$zd = gzopen($fname, "r");$gz = gzread($zd, 100 * 1024 * 1024);gzclose($zd);` (I'm setting a max filesize of 100MB; adjust if that is not enough.) – Darren Cook Jan 14 '15 at 20:44
2

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;
}
Beachhouse
  • 4,972
  • 3
  • 25
  • 39
2

You can pass the compressed data from file_get_contents to gzdecode.

$text = gzdecode(file_get_contents("file.txt.gz"));
John
  • 63
  • 7
1

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;
}
Sfisioza
  • 3,830
  • 6
  • 42
  • 57
0
file_get_contents("php://filter/zlib.inflate/resource=/path/to/file.gz");

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

Marek
  • 7,337
  • 1
  • 22
  • 33