I read bytes from a file and process them. Afterwards I would like to save the packed bytes.
What is the recommended+generic way to convert an array with mixed objects/types to a byte string? In my case: array with int and string, pack types a,C,x.
A simplified example:
// $bytes = fread($handle, 100);
$bytes = "437XYZ25.011001DBEFORE ....";
$unpackString = "a3CPN/x8spare/CDSC/x4spare/a32OPT";
$unpacked = unpack($unpackString, $bytes);
var_dump($unpacked);
/*
array(3) {
["CPN"]=> string(3) "437"
["DSC"]=> int(49)
["OPT"]=> string(32) "BEFORE "
}
*/
// example of processing
$unpacked["DSC"] = 12;
$unpacked["OPT"] = "AFTER ";
// pack + write the result
// $packString = "a3x8Cx4a32";
$packTypes = ["a3","x8","C","x4","a32"];
$packFields = [ $unpacked["CPN"], null, $unpacked["DSC"], null, $unpacked["OPT"] ];
// ...
update: in the simplified example I have replaced $packString with $packTypes and $packFields to make sure it is clear what content belongs where and with what type.
unpackto unpack the array, why can't you usepackto pack it again? Is the problem with the fact thatpackaccepts arguments instead of a single array?