dsa2c2255888 2016-11-25 16:14
浏览 264

PHP和Javascript之间的Msgpack

I'm using official MsgPack version (http://msgpack.org/), installed for PHP 7 on server side and included as a library (msgpack.js) on client (any browser). Lets pack simple ArrayBuffer with msgpack in the browser:

function s2b ( s ) {
  var b = new Uint8Array(s.length);
  for ( var i = 0; i < s.length; i++ ) {
    var c = s.charCodeAt(i);
    if ( c > 255 ) throw new Error("Wide characters are not allowed");
    b[i] = c;
  }
  return b;
}

var test = { 'name': s2b('value').buffer };
console.log('packed', new Uint8Array(msgpack.pack(test)));

and here is the console output: packed [129, 164, 110, 97, 109, 101, 196, 5, 118, 97, 108, 117, 101]

We see here that before the 'value' ascii codes we have 2 additional mspack flags - 196 (the type of data is ArrayBuffer) and 5 (the lenght of ArrayBuffer data). All is clear here.

The question is - how to construct the same object in PHP? Lets look at my code:

$data = [
  "name" => 'value',
];
$packed = msgpack_pack($data);
for($i = 0; $i < strlen($packed); $i++) echo ord($packed[$i]) . ",";

The output is: "129,164,110,97,109,101,165,118,97,108,117,101,"

Obviously [196, 5] are changed to [165]. I understood that in PHP code the type of variable is string, but HOW TO EMULATE ArrayBuffer (raw binary) data in PHP?

I have tried PHP pack() but this didn't help.

  • 写回答

1条回答 默认 最新

  • doubi2228 2017-10-31 12:29
    关注

    It's not really possible with the current msgpack-php extension (v2.0.2). See the following tickets for details:

    Although, it's quite easy to achieve with the rybakit/msgpack library (see the examples/binary.php):

    use MessagePack\Packer;
    use MessagePack\PackOptions;
    use MessagePack\Type\Binary;
    use MessagePack\TypeTransformer\BinaryTransformer;
    
    $packer = new Packer(PackOptions::FORCE_STR);
    $packer->registerTransformer(new BinaryTransformer());
    
    $packed = $packer->pack(['name' => new Binary('value')]);
    
    echo '[', implode(', ', unpack('C*', $packed)), "]
    ";
    

    Output: [129, 164, 110, 97, 109, 101, 196, 5, 118, 97, 108, 117, 101]

    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)