Sample code for 30+ languages & platforms
PHP

Compress Text from StringBuilder to Gzip (BinData Output)

See more Gzip Examples

This example demonstrates how to use the CompressSb method to compress text stored in a StringBuilder into Gzip format.

The text is first converted to its byte representation using the specified character set (in this case, UTF-8). These bytes are then compressed, and the resulting Gzip data is written to a BinData object in memory.

This approach is useful when working with dynamically generated text that you want to compress without first writing it to a file. The example also shows how the compressed data can optionally be saved to a .gz file.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\BinData;
use Chilkat2\Gzip;
use Chilkat2\StringBuilder;

// This example demonstrates how to compress text contained in a StringBuilder
// into Gzip format, storing the compressed result in a BinData object.

$gzip = new Gzip();
$sb = new StringBuilder();
$bd = new BinData();

// Add some text to the StringBuilder:
$sb->Append('The quick brown fox jumps over the lazy dog.');

// Compress the text using UTF-8 encoding:
try {
    $gzip->CompressSb($sb, 'utf-8', $bd);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// The BinData now contains the Gzip-compressed bytes.
echo "Compression successful.\n";
echo 'Compressed size (bytes): ', $bd->NumBytes, "\n";

// (Optional) Save to a .gz file:
try {
    $bd->WriteFile('text.gz');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

echo "Gzip file written to text.gz\n";