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);






1 comment:

  1. All in all, I've never had the opportunity to learn programming languages ​​and now I don't know if I would be able to understand it. I am happy to use the solutions provided by https://grapeup.com/services/application-development and in my opinion that such application development is future-proof.

    ReplyDelete