1.定義一個protoc 文件 示例:person.proto
syntax="proto3"; //聲明版本,3x版本支持php package test; //包名 message Person{ //Person 生成php文件的類名 string name=1; //姓名 int32 age=2; //年齡 bool sex=3; //性別 }
2.安裝peotoc成功后,進入cmd 執行命令
protoc --php_out=./ person.proto
命令執行成功后,會在當前目錄生成 文件 GPBMetadata/Person.php Test/Person.php
3.在php中使用protobuf需要安裝php的擴展,或者使用composer 安裝依賴擴展(自動生成 autoload 文件,方便)
composer require google/protobuf
4.建立測試 test.php文件,能夠引入生成的php類庫文件與composer 安裝生成的autoload 文件,執行文件
序列化
<?php include 'vendor/autoload.php'; include 'GPBMetadata/Person.php'; include 'Test/Person.php'; $person = new Test\Person(); $person->setName("xiaozhu"); $person->setAge("20"); $person->setSex(true); $data = $person->serializeToString(); file_put_contents('data.bin',$data); echo $data;
反序列化
<?php include 'vendor/autoload.php'; include 'GPBMetadata/Person.php'; include 'Test/Person.php'; $person = new Test\Person(); $bindata = file_get_contents('./data.bin'); $person = new Test\Person(); $person->mergeFromString($bindata); echo $person->getName();