README.md
1# Msgpack for PHP
2[![Build Status](https://secure.travis-ci.org/msgpack/msgpack-php.png)](https://travis-ci.org/msgpack/msgpack-php)
3
4This extension provide API for communicating with MessagePack serialization.
5
6MessagePack is a binary-based efficient object serialization library.
7It enables to exchange structured objects between many languages like JSON.
8But unlike JSON, it is very fast and small.
9
10## Requirement
11- PHP 7.0 +
12
13## Install
14
15### Install from PECL
16Msgpack is an PECL extension, thus you can simply install it by:
17
18```shell
19$ pecl install msgpack
20```
21
22### Compile Msgpack from source
23```shell
24$ /path/to/phpize
25$ ./configure --with-php-config=/path/to/php-config
26$ make && make install
27```
28
29### Example
30```php
31<?php
32$data = array(0 => 1, 1 => 2, 2 => 3);
33$msg = msgpack_pack($data);
34$data = msgpack_unpack($msg);
35```
36
37### Advanced Example
38```php
39<?php
40$data = array(0 => 1, 1 => 2, 2 => 3);
41$packer = new \MessagePack(false);
42// ^ same as $packer->setOption(\MessagePack::OPT_PHPONLY, false);
43$packed = $packer->pack($data);
44
45$unpacker = new \MessagePackUnpacker(false);
46// ^ same as $unpacker->setOption(\MessagePack::OPT_PHPONLY, false);
47$unpacker->feed($packed);
48$unpacker->execute();
49$unpacked = $unpacker->data();
50$unpacker->reset();
51```
52
53### Advanced Streaming Example
54```php
55<?php
56$data1 = array(0 => 1, 1 => 2, 2 => 3);
57$data2 = array("a" => 1, "b" => 2, "c" => 3);
58
59$packer = new \MessagePack(false);
60$packed1 = $packer->pack($data1);
61$packed2 = $packer->pack($data2);
62
63$unpacker = new \MessagePackUnpacker(false);
64$buffer = "";
65$nread = 0;
66
67//Simulating streaming data :)
68$buffer .= $packed1;
69$buffer .= $packed2;
70
71while(true) {
72 if($unpacker->execute($buffer, $nread)) {
73 $msg = $unpacker->data();
74
75 var_dump($msg);
76
77 $unpacker->reset();
78 $buffer = substr($buffer, $nread);
79 $nread = 0;
80 if(!empty($buffer)) {
81 continue;
82 }
83 }
84 break;
85}
86
87```
88
89## Resources
90 * [msgpack](http://msgpack.org/)
91