Last active
September 3, 2019 07:31
-
-
Save TinyPoro/9c518913eb409cccd21a609181a331f9 to your computer and use it in GitHub Desktop.
Storing object in binary file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
*Note: $obj can be any type of data : object, array, .... | |
1. Storing object in binary file | |
//convert obj to binary data | |
$obj = new Class(); | |
$serialized_data = serialize($obj); | |
$binary_data = unpack("C*",$serialized_data); | |
//store binary data in binary file | |
$file = fopen('binary', 'w+'); | |
$bin_str = ''; | |
foreach ($binary_data as $data) { | |
$bin_str .= $data." "; | |
} | |
fwrite($file, $bin_str); | |
fclose($file); | |
2. Get object back from binary file | |
//read data from binary file to array | |
$binary_array = []; | |
$lines = file('binary'); | |
foreach ($lines as $line) { | |
$datas = explode(' ', $line) | |
foreach($datas as $data{ | |
$binary_array[] = $data; | |
} | |
} | |
$serialized_data = call_user_func_array('pack', array_merge(array('C*'), $binary_array)); | |
$obj = unserialize($serialized_data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment