读取和写入压缩的gzip文件
读取和写入压缩的gzip文件的方式与读取和写入普通文件的方式几乎相同。主要区别是使用一些压缩和解压缩数据的特殊功能。而是使用fopen()来打开文件,而是使用来打开压缩文件gzopen()。许多文件访问功能都是这种情况,尽管您应该意识到它们的功能并不完全相同。以下是一些使用中的压缩功能的示例。要从压缩文件中读取,请使用以下脚本。
//从文件读取
$inputfile = 'text.gz';
$filecontents = '';
$ifh = gzopen($inputfile, 'r');
while ( $line = gzgets($ifh, 1024) ) {
$filecontents .= $line;
}
echo $filecontents;
gzclose($ifh);要写入压缩文件,请使用以下脚本。//写入无限制文件
$inputfile = 'text.gz';
$string = 'lalalala';
$filecontents = '';
$ifh = gzopen($inputfile, 'r');
while ( $line = gzgets($ifh, 1024) ) {
$filecontents .= $line;
}
gzclose($ifh);
$ifh = gzopen($inputfile, 'w');
if ( !gzwrite($ifh, $filecontents.$string) ) {
//写失败
}
gzclose($ifh);要压缩普通文件,请使用以下脚本。//压缩
$inputfile = 'text.txt';
$outputfile = 'text.gz';
//打开文件
$ifh = fopen($inputfile, 'rb');
$ofh = fopen($outputfile, 'wb');
//编码字符串
$encoded = gzencode(fread($ifh, filesize($inputfile)));
if ( !fwrite($ofh, $encoded) ) {
//写失败
}
//关闭档案
fclose($ifh);
fclose($ofh);要解压缩gzip文件,请使用以下脚本。//解压
$inputfile = 'text.gz';
$outputfile = 'text.txt';
$ofh = fopen($outputfile, 'wb');
$string = '';
$ifh = gzopen($inputfile, 'r');
while ( $line = gzgets($ifh, 1024) ) {
$string .= $line;
}
if ( !fwrite($ofh, $string) ) {
//写失败
}
echo $string;
gzclose($ifh);
fclose($ofh);请注意,从这些示例中,您可以使用以下命令打开压缩文件:fopen(),但是您需要使用'b'标志来指示要以二进制格式打开文件来打开文件。基本上,以下两个调用非常相同。$ifh = gzopen($inputfile, 'r'); $ifh = fopen($inputfile, 'rb');该gzopen()功能还可以将其他一些参数用作模式。这些包括压缩级别(例如wb1或wb9)或策略。该策略可以是f(用于过滤)(用作wb9f),也可以是h(仅用于霍夫曼压缩)(用作wb1h)。
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短