Passing Binary Data Between Chilkat and PHP

This example explains how to pass binary data between Chilkat and PHP.


<?php

include("chilkat.php");

$bd = new CkBinData();

// Create a binary string in PHP.
$binary_string = pack("C*", 0, 1, 2, 3, 4);

// Copy the bytes to the CkBinData object.
$bd->AppendData($binary_string,strlen($binary_string));
    
// View the contents of bd in hexadecimal format.
// Output: 0001020304
print $bd->getEncoded("hex") . "\r\n";
    
// Append a few more bytes
$bd->AppendEncoded("05060708","hex");
    
// Call GetData to copy the bytes to a new binary string
$binary_string = $bd->GetData();
    
// Print each byte value
// ord() gets the byte value of each character
for ($i = 0; $i < strlen($binary_string); $i++) {
    echo ord($binary_string[$i]) . "\n";
}

print "----\n";
 
// Output is:
// 0
// 1
// 2
// ...
// 8
    
// You can get a range of bytes by calling GetDataChunk
// GetDataChunk has 0-based indexing.  The 1st byte is at index 0.
$binary_string = $bd->GetDataChunk(2,4);
for ($i = 0; $i < strlen($binary_string); $i++) {
    echo ord($binary_string[$i]) . "\n";
}
    
// Output is:
// 2
// 3
// 4
// 5

?>