【发布时间】:2023-04-07 16:27:02
【问题描述】:
与file_get_contents 等效的函数是什么,它读取使用gzwrite 函数编写的文本文件的全部内容?
【问题讨论】:
与file_get_contents 等效的函数是什么,它读取使用gzwrite 函数编写的文本文件的全部内容?
【问题讨论】:
使用stream wrappers 会更容易
file_get_contents('compress.zlib://'.$file);
【讨论】:
显然是 gzread .. 还是你的意思是 file_put_contents ?
编辑: 如果您不想有句柄,请使用readgzfile。
【讨论】:
readgzfile 输出到标准输出,而不是字符串。但是使用gzread 对我来说效果很好。例如。 $zd = gzopen($fname, "r");$gz = gzread($zd, 100 * 1024 * 1024);gzclose($zd);(我将最大文件大小设置为 100MB;如果不够,请调整。)
我尝试了@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;
}
【讨论】:
我根据手册中的 cmets 写了一个我正在寻找的函数:
/**
* @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;
}
【讨论】:
file_get_contents("php://filter/zlib.inflate/resource=/path/to/file.gz");
我不确定它会如何处理 gz 文件头。
【讨论】: