Skip to content

Working with NBT data

timmyRS edited this page Apr 3, 2020 · 1 revision

Converting SNBT to NBT data

To convert SNBT data such as {greeting: "Hello, world!"} into NBT data, we could either use some tools from the Phpcraft Toolbox, or write a simple PHP script as follows.

First, make sure your composer project is properly set up, and then we can add our script's first line to simply load Phpcraft and your other dependencies:

require "vendor/autoload.php";

Next, we'll convert our SNBT to NBT data using the handy NBT::fromSNBT function:

$nbt = \Phpcraft\NBT\NBT::fromSNBT('{greeting: "Hello, world!"}');

Now, we could decide to simply get a string dump:

echo $nbt;

{Compound "": {String "greeting": Hello, world!}}

Or we could write it to a file:

Writing NBT data

For this, we'll need a Connection. We'll open a stream to the file my.nbt in write mode, and use protocol version -1, meaning the latest supported protocol version:

$con = new \Phpcraft\Connection(-1, fopen("my.nbt", "w"));

Finally, we get to writing the data. Because Phpcraft is oriented around the network protocol, you need to call ->send(true) to submit the write buffer to the underlying stream.

$nbt->write($con);
$con->send(true);

And that's it! If we now run nbt my.nbt from the toolbox, we get:

::: String Dump
{Compound "": {String "greeting": Hello, world!}}
::: SNBT
{greeting:"Hello, world!"}
::: Pretty SNBT
{
        greeting: "Hello, world!"
}

Reading NBT data

In this case, we'll be reading NBT data from the my.nbt file we created before this.

First, we're once again creating a connection using the latest protocol version and a file stream, this time in read mode:

$con = new \Phpcraft\Connection(-1, fopen("my.nbt", "r"));

Because our NBT data is just sitting in the file, without any proper packet format as Phpcraft would normally expect, we're going to be reading a "raw packet":

$con->readRawPacket();

With our "packet" now in the read buffer, we can simply read an NBT object from it:

$nbt = $con->readNBT();

For our own sanity's sake, we'll assert that all bytes have populated our NBT object and no data is left:

assert(!$con->hasRemainingData());

Finally, we can do whatever we want with our NBT object, including converting it back to SNBT:

echo $nbt->toSNBT();

{greeting:"Hello, world!"}

Clone this wiki locally