Tuesday, November 29, 2011

PHP to Write Binary Data (or Array Data) to a File using Pack Function




Writing the Binary Data directly using PHP's Pack() function:



// Write Binary Data
$bin_data = pack("C*", 0x47, 0x49, 0x46);

$fp = fopen("c://test.bin", 'wb'); // replace with your filename
// (please also check file permission before write)
fwrite($fp, $bin_data);
fclose($fp);







Writing the Binary Data from an Array (if the data length is too long):



// Write Binary Data
$bin_data_array = array(0x47, 0x49, 0x46, .....................................);

foreach ($bin_data_array as $data) {

$bin_data .= pack("C", $data);

}

$fp = fopen("c://test.bin", 'wb'); // replace with your filename
// (please also check file permission before write)
fwrite($fp, $bin_data);
fclose($fp);









This WON'T work:



// Write Binary Data
$bin_data_array = array(0x47, 0x49, 0x46, .....................................);

$bin_data = pack("C*", $bin_data_array);

$fp = fopen("c://test.bin", 'wb'); // replace with your filename
//(please also check file permission before write)
fwrite($fp, $bin_data);
fclose($fp);






No comments:

Post a Comment