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 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)