dsmithhayes / bencode
一个简单的PHP bencoding库。
v0.1.3
2015-10-13 01:26 UTC
Requires (Dev)
- phpunit/phpunit: ^4.7
This package is not auto-updated.
Last update: 2024-09-18 10:07:28 UTC
README
这是一个用于编码和解码bencoded流库。Bencoding主要存在于.torrent
文件结构中。
Bencoding基础
读作bee-encoding,这种编码主要关注使用四种基本元素数据结构的二进制编码。
整数
字节
列表
字典
最后两个元素(列表
,字典
)仅仅是前两个元素的集合。
整数
整数元素是一个带符号的整数,始终以i
开头,以e
结尾。
i45e
i-1e
用法
<?php
use Bencode\Integer;
$int = new Integer(45);
echo $int->encode(); // i45e
$int->decode(i-445e);
echo $int->write(); // -445
字节
字节编码时,用其大小(字节)、一个:
然后是字节序列。
5:hello
6:123456
注意,第二个例子将编码字符码而不是整数的二进制值。
用法
<?php
use Bencode\Byte;
$byte = new Byte('hello');
echo $byte->encode(); // 5:hello
$byte->decode('5:world');
echo $byte->write(); // world
列表
列表就是一个列表,包含了字节和整数元素。它的编码与整数类似。列表以l
开头,以e
结尾。列表内部编码了字节和整数。
li45e5:hello5:worldi-45e
用法
由于列表
在PHP中是一个保留关键字,因此类命名为BList
。
<?php
use Bencode\Collection\BList
$list = new BList([45, 'hello', 'world', -45]);
echo $list->encode(); // li45e5:hello5:worldi-45e
$list->decode('li34e4:davee');
print_r($list->write()); // [34, 'dave']
字典
字典是键值列表。列表中的第一个元素是键,第二个是值。字典以d
开头,以e
结尾。
d3:key5:valuee
您也可以将元素作为列表中的值使用。
d3:keyli3ei5eee
d3:keyd3:key5:valueee
用法
<?php
use Bencode\Collection\Dictionary;
$dictionary = new Dictionary(['key' => 'value']);
echo $dictionary->encode(); // d3:key5:valuee
$dictionary->decode('d3:new6:valuese');
print_r($dictionary->write()); // ['new' => 'values']
字典正是您的.torrent
文件所编码的。您可以轻松构建对象来操作torrent文件的数据。
<?php
use Bencode\Collection\Dictionary;
$dictionary = new Dictionary();
$torrent = file_get_contents('example.torrent');
$ditionary->decode($torrent);
$buffer = $dictionary->write();
echo $buffer['comment'];