PHPStruct class

Build Status Codacy Badge License Packagist download count Packagist HHVM Status StyleCI

Licensed under MIT.

PHP implementation of Python's struct module.

This library was created to help me develop a client for the mtproto protocol.
It supports php 5.6, php 7 and HHVM.

The functions and the formats are exactly the ones used in python's struct (https://docs.python.org/3/library/struct.html)

This library can be used to pack/unpack strings, ints, floats, chars and bools into bytes. It has lots of advantages over PHP's native implementation of pack and unpack, such as:

For now custom byte size may not work properly on certain machines for the f and d formats.

Installation

Install using composer:

composer require danog/phpstruct

Usage

Dynamic (recommended)

require('vendor/autoload.php');
$struct = new \danog\PHP\StructClass();
$pack = $struct->pack("2cxi", "ab", 44);
$unpack = $struct->unpack("2cxi", $pack);
var_dump($unpack);
$count = $struct->calcsize("2cxi");

Dynamic (while specifying format string during istantiation)

require('vendor/autoload.php');
$struct = new \danog\PHP\StructClass("2cxi");
$pack = $struct->pack("ab", 44);
$unpack = $struct->unpack($pack);
var_dump($unpack);
$count = $struct->size;
$formatstring = $struct->format;

Static

require('vendor/autoload.php');
$pack = \danog\PHP\Struct::pack("2cxi", "ab", 44);
$unpack = \danog\PHP\Struct::unpack("2cxi", $pack);
var_dump($unpack);
$count = \danog\PHP\Struct::calcsize("2cxi");

Daniil Gentili