Install php-protobu extensions for php and use resources: https://github.com/allegro/php-protobuf/
Go to the extract directory and run phpize.
./Configure
Make
Make install
# Please add following line to your php. ini
Extension = protobuf. so
Restart PHP
Phpinfo () shows the protobuff extension.
How to use it?
Save
First, the proto file foo. proto file is created.
Message PhoneNumber {
Required string number = 1;
Required int32 type = 2;
}
Message Person {
Required string name = 1;
Required int32 id = 2;
Optional string email = 3;
Repeated PhoneNumber phone = 4;
}
Message AddressBook {
Repeated Person person = 1;
}
Then generate
Php protoc-php.php foo. proto
At this time, a pb_proto_foo.php file will be generated.
The specific application is as follows.
For example, to communicate with JAVA. Protobuffer stores the php file test. php, for example:
Require_once 'pb _ proto_test.php ';
$ Packed = curlGet ('http: // 10.0.247.113: 8080/testweb/proto'); // buffer information returned by JAVA
$ Foo = new AddressBook ();
Try {
$ Foo-> parseFromString ($ packed );
} Catch (Exception $ ex ){
Die ('parse error: '. $ e-> getMessage ());
}
$ Pb = $ foo-> getPerson ();
// Print_r ($ pb );
// Print_r ($ pb [0]);
Echo $ pb [0]-> getName (). '_'. $ pb [0]-> getId ().'_';
Print_r ($ pb [0]-> getPhone ());
PHP calls to modify buffer data
----------------------------
Require_once 'pb _ proto_test.php ';
$ Foo = new Person ();
$ Foo-> setName ('xiaoyun ');
$ Foo-> setId (200 );
$ Foo-> setEmail ('dofound @ 163.com ');
// $ Foo-> appendPhone (2 );
$ Packed = $ foo-> serializeToString ();
$ Foo-> clear ();
Try {
$ Xiao = $ foo-> parseFromString ($ packed );
// Print_r ($ xiao );
} Catch (Exception $ ex ){
Die ('upss .. there is a bug in this example ');
}
Echo $ foo-> getName ();
Echo $ foo-> getPhone ()-> number;
$ Foo-> dump ();
PHP internal call
------------------------------
Generate buffer data