NBT文件格式解析器/写入器

4.1.0 2023-12-04 08:34 UTC

README

这是一个基于Markus Persson规范的命名二进制标签解析器。

规范中提到:“NBT(命名二进制标签)是一种基于标签的二进制格式,旨在携带大量二进制数据的同时携带少量额外的数据。NBT文件由一个GZIP压缩的名为TAG_Compound的标签组成。”

NBT数据也用于存储Minecraft世界数据的区域文件中。

32位构建需要GMP扩展的PHP。

安装

Composer

可以使用composer引入此库;将以下内容添加到您的composer.json中

{
    "require": {
        "rickselby/nbt": "~4.0"
    }
}

使用方法

从文件、资源或字符串中读取

$nbtService = new \Nbt\Service(new \Nbt\DataHandler());
$tree = $nbtService->loadFile('filename.nbt');
$tree = $nbtService->readFilePointer($fPtr);
$tree = $nbtService->readString($nbtString);

然后将数据写入文件、资源或返回字符串

$nbtService->writeFile('filename.nbt', $tree);
$nbtService->writeFilePointer($fPtr, $tree);
$nbtString = $nbtService->writeString($tree);

遍历树

echo $tree->getName();
$type = $tree->getType();

// Value isn't set for Lists and Compounds; those nodes have children instead
$value = $tree->getValue();

$sectionsNode = $tree->findChildByName('Sections');

更新树

$node->setName('Name');
$node->setValue(123456);

创建新节点

// This is pretty useless on it's own really
$node = \Nbt\Tag::tagByte('aByte', 0x0f);

// You'll be building trees with Compounds and Lists mostly; both take an array of nodes as their values
$tree = \Nbt\Tag::tagCompound('aCompound', [
    \Nbt\Tag::tagByte('aByte', 0x0f),
    \Nbt\Tag::tagInt('aNumber', 12345),
]);

// Child tags for lists do not require names, as they are not named - and they must match the payload of the list
$tree = \Nbt\Tag::tagList('aList', \Nbt\Tag::TAG_STRING, [
    \Nbt\Tag::tagString('', 'firstString'),
    \Nbt\Tag::tagString('', 'secondString'),
]);

历史

原始PHP NBT包由TheFrozenFire编写。

这个仓库被很多人fork,但大多数fork存在一个问题;要么不处理TAG_INT_ARRAY,要么不正确地处理写入文件指针。

返回的格式——一个数组——并不理想,用于创建自己的NBT数据,需要某种包装器来辅助创建。

我对代码进行了整理,然后添加了nicmart/tree来存储NBT数据;经过大量工作,它与原始版本大不相同,所以我将其拉入了自己的(非forked)仓库。