katzlbtjunk's method is certainly shorter, but it is unusable for anything except small files. It would try to load the whole file into memory, then create an entire compressed copy, and only then write it to disk. The other method given below will not exhaust memory like that.
gzwrite
(PHP 4, PHP 5)
gzwrite — バイナリセーフな gz ファイル書き込み
説明
int gzwrite
( resource $zp
, string $string
[, int $length
] )
gzwrite() は string の内容を与えられた gz ファイルに書き込みます。
パラメータ
- zp
-
gz ファイルポインタを指定します。これは有効なファイルポインタであり、 かつ、gzopen() によりオープンできたファイルを指している必要があります。
- string
-
書き込む文字列を指定します。
- length
-
書き込む解凍されたバイト数を指定します。 もし指定された場合、 length バイトのデータが書き込まれたか、 string の終わりに達した時に 書き込みは終了します。
注意: 引数 length が指定された場合、 magic_quotes_runtime 設定オプションは無視されて string から スラッシュが取り除かれなくなることに注意してください。
返り値
与えられた gz ファイルストリームに書き込まれた (解凍された) バイト数を返します。
例
例1 gzwrite() の例
<?php
$string = 'Some information to compress';
$gz = gzopen('somefile.gz','w9');
gzwrite($gz, $string);
gzclose($gz);
?>
gzwrite
Anonymous
28-Mar-2008 05:34
28-Mar-2008 05:34
katzlbtjunk at hotmail dot com
22-Feb-2008 04:24
22-Feb-2008 04:24
How about this instead:
$s = file_get_contents('file.tar');
file_put_contents('file.tar.gz',gzencode($s,9));
Kioob
13-Aug-2003 08:30
13-Aug-2003 08:30
This is a short example of use gzwrite function.
<?php
function gzcompressfile($source,$level=false){
$dest=$source.'.gz';
$mode='wb'.$level;
$error=false;
if($fp_out=gzopen($dest,$mode)){
if($fp_in=fopen($source,'rb')){
while(!feof($fp_in))
gzwrite($fp_out,fread($fp_in,1024*512));
fclose($fp_in);
}
else $error=true;
gzclose($fp_out);
}
else $error=true;
if($error) return false;
else return $dest;
}
?>
the function gzcompressfile() compress a file 'data.csv' to 'data.csv.gz'. the function return false if error, and the new file name if it's ok.
