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.