Home >Backend Development >PHP Problem >How to read and write protobuf3 in PHP
protobuf (Google Protocol Buffers) is an efficient protocol data exchange format tool library provided by Google (similar to Json), but compared to Json, Protobuf has higher conversion efficiency, time efficiency and space efficiency are both JSON's 3-5 times.
In proto3, you can directly use the protoc command to generate PHP code. The generated PHP code cannot be used directly and requires Protobuf PHP library support.
The following uses an example to demonstrate how to use protobuf in PHP. First define the proto file:
syntax = "proto3"; package lm; message helloworld { int32 id = 1; // ID string str = 2; // str int32 opt = 3; // optional field }
Note that the syntax of proto3 is used here, which is different from proto2. The restrictions of required and optional are no longer available, and all fields are optional. What are the differences between proto3 and proto2? You can refer to this article.
Then use protoc to generate the PHP file:
protoc --php_out=./ hello.proto
You will see that a hello.pb.php file is generated:
namespace Lm; use Google\Protobuf\Internal\DescriptorPool; use Google\Protobuf\Internal\GPBType; use Google\Protobuf\Internal\RepeatedField; use Google\Protobuf\Internal\GPBUtil; class helloworld extends \Google\Protobuf\Internal\Message { .... }
Read Download the code inside and find that it uses classes under Google\Protobuf. This is a PHP library. You can download it:
https://github.com/google/protobuf/tree/master/php/ src/Google/Protobuf
can also be introduced into the project using composer. It is recommended to use composer because composer will automatically generate Autoloader for you:
composer require google/protobuf
After introducing google/protobuf using composer, A vendor directory will appear in the project. In your own code, you can read and write binary by including autoload.php under includevendor and the helloworld.pb.php file just generated.
With the help of the google/protobuf library, it is very convenient for PHP to read and write binary in protobuf format.
Use protobuf to write data to a binary file:
<?php include 'vendor/autoload.php'; include 'hello.pb.php'; $from = new \Lm\helloworld(); $from->setId(1); $from->setStr('foo bar, this is a message'); $from->setOpt(29); $data = $from->serializeToString(); file_put_contents('data.bin', $data);
Read the same binary file:
<?php include 'vendor/autoload.php'; include 'hello.pb.php'; $data = file_get_contents('data.bin'); $to = new \Lm\helloworld(); $to->mergeFromString($data); echo $to->getId() . PHP_EOL; echo $to->getStr() . PHP_EOL; echo $to->getOpt() . PHP_EOL;
Recommended learning: php video tutorial
The above is the detailed content of How to read and write protobuf3 in PHP. For more information, please follow other related articles on the PHP Chinese website!