例
テンポラリファイルをオープンし、テスト用文字列を書きこみ、 続いて、このファイルの内容を 2 回出力します。
例1 簡単な Zlib の例
<?php$filename = tempnam('/tmp', 'zlibtest') . '.gz';echo "<html>\n<head></head>\n<body>\n<pre>\n";$s = "Only a test, test, test, test, test, test, test, test!\n";// 最大限の圧縮を指定して書きこみ用にファイルをオープン$zp = gzopen($filename, "w9");// 文字列をファイルに書きこむgzwrite($zp, $s);// ファイルを閉じるgzclose($zp);// 読みこみ用にファイルをオープン$zp = gzopen($filename, "r");// 3 文字読みこむecho gzread($zp, 3);// ファイルの終端まで出力して閉じるgzpassthru($zp);gzclose($zp);echo "\n";// ファイルをオープンし、内容を出力する (2回目)if (readgzfile($filename) != strlen($s)) { echo "Error with zlib functions!";}unlink($filename);echo "</pre>\n</body>\n</html>\n";?>
例2 PHP 7.0.0 以降の、インクリメンタルな圧縮および伸長の API
<?php// GZIP 圧縮$deflateContext = deflate_init(ZLIB_ENCODING_GZIP);$compressed = deflate_add($deflateContext, "Data to compress", ZLIB_NO_FLUSH);$compressed .= deflate_add($deflateContext, ", more data", ZLIB_NO_FLUSH);$compressed .= deflate_add($deflateContext, ", and even more data!", ZLIB_FINISH);// GZIP 伸長$inflateContext = inflate_init(ZLIB_ENCODING_GZIP);$uncompressed = inflate_add($inflateContext, $compressed, ZLIB_NO_FLUSH);$uncompressed .= inflate_add($inflateContext, NULL, ZLIB_FINISH);echo $uncompressed;?>
上の例の出力は以下となります。
Data to compress, more data, and even more data!