Minecraft NBT (Named Binary Tag): PHP parsing library

A structured binary format native to Minecraft for saving game data and transferring it over the network (in multiplayer), such as player data (<player>.dat; contains e.g. player's inventory and location), saved worlds (level.dat and Chunk format), list of saved multiplayer servers (servers.dat) and so on - see https://minecraft.gamepedia.com/NBT_format#Uses.

The entire file should be gzip-compressed (in accordance with the original specification NBT.txt by Notch), but can also be compressed with zlib or uncompressed.

This spec can only handle uncompressed NBT data, so be sure to first detect what type of data you are dealing with. You can use the Unix file command to do this (file-5.20 or later is required; older versions do not recognize zlib-compressed data and return application/octet-stream instead):

file --brief --mime-type input-unknown.nbt

If it says:

  • application/x-gzip or application/gzip (since file-5.37), you can decompress it by
    • gunzip -c input-gzip.nbt > output.nbt or
    • python3 -c "import sys, gzip; sys.stdout.buffer.write( gzip.decompress(sys.stdin.buffer.read()) )" < input-gzip.nbt > output.nbt
  • application/zlib, you can use
    • openssl zlib -d -in input-zlib.nbt -out output.nbt (does not work on most systems)
    • python3 -c "import sys, zlib; sys.stdout.buffer.write( zlib.decompress(sys.stdin.buffer.read()) )" < input-zlib.nbt > output.nbt
  • something else (especially image/x-pcx and application/octet-stream), it is most likely already uncompressed.

The file output.nbt generated by one of the above commands can already be processed with this Kaitai Struct specification.

This spec only implements the Java edition format. There is also a Bedrock edition NBT format, which uses little-endian encoding and has a few other differences, but it isn't as popular as the Java edition format.

Implementation note: strings in TAG_String are incorrectly decoded with standard UTF-8, while they are encoded in Modified UTF-8 (MUTF-8). That's because MUTF-8 is not supported natively by most target languages, and thus one must use external libraries to achieve a fully-compliant decoder. But decoding in standard UTF-8 is still better than nothing, and it usually works fine.

All Unicode code points with incompatible representations in MUTF-8 and UTF-8 are U+0000 (NUL), U+D800-U+DFFF (High and Low Surrogates) and U+10000-U+10FFFF (all Supplementary Planes; includes e.g. emoticons, pictograms). A MUTF-8-encoded string containing these code points cannot be successfully decoded as UTF-8. The behavior in this case depends on the target language - usually an exception is thrown, or the bytes that are not valid UTF-8 are replaced or ignored.

Sample files:

Application

Minecraft

File extension

["nbt", "dat", "schematic", "schem"]

KS implementation details

License: CC0-1.0

References

This page hosts a formal specification of Minecraft NBT (Named Binary Tag) using Kaitai Struct. This specification can be automatically translated into a variety of programming languages to get a parsing library.

PHP source code to parse Minecraft NBT (Named Binary Tag)

MinecraftNbt.php

<?php
// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild

/**
 * A structured binary format native to Minecraft for saving game data and transferring
 * it over the network (in multiplayer), such as player data
 * ([`<player>.dat`](https://minecraft.gamepedia.com/Player.dat_format); contains
 * e.g. player's inventory and location), saved worlds
 * ([`level.dat`](
 *   https://minecraft.gamepedia.com/Java_Edition_level_format#level.dat_format
 * ) and [Chunk format](https://minecraft.gamepedia.com/Chunk_format#NBT_structure)),
 * list of saved multiplayer servers
 * ([`servers.dat`](https://minecraft.gamepedia.com/Servers.dat_format)) and so on -
 * see <https://minecraft.gamepedia.com/NBT_format#Uses>.
 * 
 * The entire file should be _gzip_-compressed (in accordance with the original
 * specification [NBT.txt](
 *   https://web.archive.org/web/20110723210920/https://www.minecraft.net/docs/NBT.txt
 * ) by Notch), but can also be compressed with _zlib_ or uncompressed.
 * 
 * This spec can only handle uncompressed NBT data, so be sure to first detect
 * what type of data you are dealing with. You can use the Unix `file` command
 * to do this (`file-5.20` or later is required; older versions do not recognize
 * _zlib_-compressed data and return `application/octet-stream` instead):
 * 
 * ```shell
 * file --brief --mime-type input-unknown.nbt
 * ```
 * 
 * If it says:
 * 
 *   * `application/x-gzip` or `application/gzip` (since `file-5.37`), you can decompress it by
 *     * `gunzip -c input-gzip.nbt > output.nbt` or
 *     * `python3 -c "import sys, gzip; sys.stdout.buffer.write(
 *       gzip.decompress(sys.stdin.buffer.read()) )" < input-gzip.nbt > output.nbt`
 *   * `application/zlib`, you can use
 *     * `openssl zlib -d -in input-zlib.nbt -out output.nbt` (does not work on most systems)
 *     * `python3 -c "import sys, zlib; sys.stdout.buffer.write(
 *       zlib.decompress(sys.stdin.buffer.read()) )" < input-zlib.nbt > output.nbt`
 *   * something else (especially `image/x-pcx` and `application/octet-stream`),
 *     it is most likely already uncompressed.
 * 
 * The file `output.nbt` generated by one of the above commands can already be
 * processed with this Kaitai Struct specification.
 * 
 * This spec **only** implements the Java edition format. There is also
 * a [Bedrock edition](https://wiki.vg/NBT#Bedrock_edition) NBT format,
 * which uses little-endian encoding and has a few other differences, but it isn't
 * as popular as the Java edition format.
 * 
 * **Implementation note:** strings in `TAG_String` are incorrectly decoded with
 * standard UTF-8, while they are encoded in [**Modified UTF-8**](
 *   https://docs.oracle.com/javase/8/docs/api/java/io/DataInput.html#modified-utf-8
 * ) (MUTF-8). That's because MUTF-8 is not supported natively by most target
 * languages, and thus one must use external libraries to achieve a fully-compliant
 * decoder. But decoding in standard UTF-8 is still better than nothing, and
 * it usually works fine.
 * 
 * All Unicode code points with incompatible representations in MUTF-8 and UTF-8 are
 * U+0000 (_NUL_), U+D800-U+DFFF (_High_ and _Low Surrogates_) and U+10000-U+10FFFF
 * (all _Supplementary_ Planes; includes e.g. emoticons, pictograms).
 * A _MUTF-8_-encoded string containing these code points cannot be successfully
 * decoded as UTF-8. The behavior in this case depends on the target language -
 * usually an exception is thrown, or the bytes that are not valid UTF-8
 * are replaced or ignored.
 * 
 * **Sample files:**
 * 
 *   * <https://wiki.vg/NBT#Download>
 *   * <https://github.com/twoolie/NBT/blob/f9e892e/tests/world_test/data/scoreboard.dat>
 *   * <https://github.com/chmod222/cNBT/tree/3f74b69/testdata>
 *   * <https://github.com/PistonDevelopers/hematite_nbt/tree/0b85f89/tests>
 */

namespace {
    class MinecraftNbt extends \Kaitai\Struct\Struct {
        public function __construct(\Kaitai\Struct\Stream $_io, \Kaitai\Struct\Struct $_parent = null, \MinecraftNbt $_root = null) {
            parent::__construct($_io, $_parent, $_root);
            $this->_read();
        }

        private function _read() {
            if ( (($this->rootType() == \MinecraftNbt\Tag::END) && (false)) ) {
                $this->_m_rootCheck = $this->_io->readBytes(0);
            }
            $this->_m_root = new \MinecraftNbt\NamedTag($this->_io, $this, $this->_root);
        }
        protected $_m_rootType;
        public function rootType() {
            if ($this->_m_rootType !== null)
                return $this->_m_rootType;
            $_pos = $this->_io->pos();
            $this->_io->seek(0);
            $this->_m_rootType = $this->_io->readU1();
            $this->_io->seek($_pos);
            if (!($this->rootType() == \MinecraftNbt\Tag::COMPOUND)) {
                throw new \Kaitai\Struct\Error\ValidationNotEqualError(\MinecraftNbt\Tag::COMPOUND, $this->rootType(), $this->_io(), "/instances/root_type");
            }
            return $this->_m_rootType;
        }
        protected $_m_rootCheck;
        protected $_m_root;
        public function rootCheck() { return $this->_m_rootCheck; }
        public function root() { return $this->_m_root; }
    }
}

namespace MinecraftNbt {
    class TagLongArray extends \Kaitai\Struct\Struct {
        public function __construct(\Kaitai\Struct\Stream $_io, \Kaitai\Struct\Struct $_parent = null, \MinecraftNbt $_root = null) {
            parent::__construct($_io, $_parent, $_root);
            $this->_read();
        }

        private function _read() {
            $this->_m_numTags = $this->_io->readS4be();
            $this->_m_tags = [];
            $n = $this->numTags();
            for ($i = 0; $i < $n; $i++) {
                $this->_m_tags[] = $this->_io->readS8be();
            }
        }
        protected $_m_tagsType;
        public function tagsType() {
            if ($this->_m_tagsType !== null)
                return $this->_m_tagsType;
            $this->_m_tagsType = \MinecraftNbt\Tag::LONG;
            return $this->_m_tagsType;
        }
        protected $_m_numTags;
        protected $_m_tags;
        public function numTags() { return $this->_m_numTags; }
        public function tags() { return $this->_m_tags; }
    }
}

namespace MinecraftNbt {
    class TagByteArray extends \Kaitai\Struct\Struct {
        public function __construct(\Kaitai\Struct\Stream $_io, \Kaitai\Struct\Struct $_parent = null, \MinecraftNbt $_root = null) {
            parent::__construct($_io, $_parent, $_root);
            $this->_read();
        }

        private function _read() {
            $this->_m_lenData = $this->_io->readS4be();
            $this->_m_data = $this->_io->readBytes($this->lenData());
        }
        protected $_m_lenData;
        protected $_m_data;
        public function lenData() { return $this->_m_lenData; }
        public function data() { return $this->_m_data; }
    }
}

namespace MinecraftNbt {
    class TagIntArray extends \Kaitai\Struct\Struct {
        public function __construct(\Kaitai\Struct\Stream $_io, \Kaitai\Struct\Struct $_parent = null, \MinecraftNbt $_root = null) {
            parent::__construct($_io, $_parent, $_root);
            $this->_read();
        }

        private function _read() {
            $this->_m_numTags = $this->_io->readS4be();
            $this->_m_tags = [];
            $n = $this->numTags();
            for ($i = 0; $i < $n; $i++) {
                $this->_m_tags[] = $this->_io->readS4be();
            }
        }
        protected $_m_tagsType;
        public function tagsType() {
            if ($this->_m_tagsType !== null)
                return $this->_m_tagsType;
            $this->_m_tagsType = \MinecraftNbt\Tag::INT;
            return $this->_m_tagsType;
        }
        protected $_m_numTags;
        protected $_m_tags;
        public function numTags() { return $this->_m_numTags; }
        public function tags() { return $this->_m_tags; }
    }
}

namespace MinecraftNbt {
    class TagList extends \Kaitai\Struct\Struct {
        public function __construct(\Kaitai\Struct\Stream $_io, \Kaitai\Struct\Struct $_parent = null, \MinecraftNbt $_root = null) {
            parent::__construct($_io, $_parent, $_root);
            $this->_read();
        }

        private function _read() {
            $this->_m_tagsType = $this->_io->readU1();
            $this->_m_numTags = $this->_io->readS4be();
            $this->_m_tags = [];
            $n = $this->numTags();
            for ($i = 0; $i < $n; $i++) {
                switch ($this->tagsType()) {
                    case \MinecraftNbt\Tag::LONG_ARRAY:
                        $this->_m_tags[] = new \MinecraftNbt\TagLongArray($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::COMPOUND:
                        $this->_m_tags[] = new \MinecraftNbt\TagCompound($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::DOUBLE:
                        $this->_m_tags[] = $this->_io->readF8be();
                        break;
                    case \MinecraftNbt\Tag::LIST:
                        $this->_m_tags[] = new \MinecraftNbt\TagList($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::FLOAT:
                        $this->_m_tags[] = $this->_io->readF4be();
                        break;
                    case \MinecraftNbt\Tag::SHORT:
                        $this->_m_tags[] = $this->_io->readS2be();
                        break;
                    case \MinecraftNbt\Tag::INT:
                        $this->_m_tags[] = $this->_io->readS4be();
                        break;
                    case \MinecraftNbt\Tag::BYTE_ARRAY:
                        $this->_m_tags[] = new \MinecraftNbt\TagByteArray($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::BYTE:
                        $this->_m_tags[] = $this->_io->readS1();
                        break;
                    case \MinecraftNbt\Tag::INT_ARRAY:
                        $this->_m_tags[] = new \MinecraftNbt\TagIntArray($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::STRING:
                        $this->_m_tags[] = new \MinecraftNbt\TagString($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::LONG:
                        $this->_m_tags[] = $this->_io->readS8be();
                        break;
                }
            }
        }
        protected $_m_tagsType;
        protected $_m_numTags;
        protected $_m_tags;
        public function tagsType() { return $this->_m_tagsType; }
        public function numTags() { return $this->_m_numTags; }
        public function tags() { return $this->_m_tags; }
    }
}

namespace MinecraftNbt {
    class TagString extends \Kaitai\Struct\Struct {
        public function __construct(\Kaitai\Struct\Stream $_io, \Kaitai\Struct\Struct $_parent = null, \MinecraftNbt $_root = null) {
            parent::__construct($_io, $_parent, $_root);
            $this->_read();
        }

        private function _read() {
            $this->_m_lenData = $this->_io->readU2be();
            $this->_m_data = \Kaitai\Struct\Stream::bytesToStr($this->_io->readBytes($this->lenData()), "utf-8");
        }
        protected $_m_lenData;
        protected $_m_data;

        /**
         * unsigned according to https://wiki.vg/NBT#Specification
         */
        public function lenData() { return $this->_m_lenData; }
        public function data() { return $this->_m_data; }
    }
}

namespace MinecraftNbt {
    class TagCompound extends \Kaitai\Struct\Struct {
        public function __construct(\Kaitai\Struct\Stream $_io, \Kaitai\Struct\Struct $_parent = null, \MinecraftNbt $_root = null) {
            parent::__construct($_io, $_parent, $_root);
            $this->_read();
        }

        private function _read() {
            $this->_m_tags = [];
            $i = 0;
            do {
                $_ = new \MinecraftNbt\NamedTag($this->_io, $this, $this->_root);
                $this->_m_tags[] = $_;
                $i++;
            } while (!($_->isTagEnd()));
        }
        protected $_m_dumpNumTags;
        public function dumpNumTags() {
            if ($this->_m_dumpNumTags !== null)
                return $this->_m_dumpNumTags;
            $this->_m_dumpNumTags = (count($this->tags()) - ( ((count($this->tags()) >= 1) && ($this->tags()[count($this->tags()) - 1]->isTagEnd()))  ? 1 : 0));
            return $this->_m_dumpNumTags;
        }
        protected $_m_tags;
        public function tags() { return $this->_m_tags; }
    }
}

namespace MinecraftNbt {
    class NamedTag extends \Kaitai\Struct\Struct {
        public function __construct(\Kaitai\Struct\Stream $_io, \Kaitai\Struct\Struct $_parent = null, \MinecraftNbt $_root = null) {
            parent::__construct($_io, $_parent, $_root);
            $this->_read();
        }

        private function _read() {
            $this->_m_type = $this->_io->readU1();
            if (!($this->isTagEnd())) {
                $this->_m_name = new \MinecraftNbt\TagString($this->_io, $this, $this->_root);
            }
            if (!($this->isTagEnd())) {
                switch ($this->type()) {
                    case \MinecraftNbt\Tag::LONG_ARRAY:
                        $this->_m_payload = new \MinecraftNbt\TagLongArray($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::COMPOUND:
                        $this->_m_payload = new \MinecraftNbt\TagCompound($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::DOUBLE:
                        $this->_m_payload = $this->_io->readF8be();
                        break;
                    case \MinecraftNbt\Tag::LIST:
                        $this->_m_payload = new \MinecraftNbt\TagList($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::FLOAT:
                        $this->_m_payload = $this->_io->readF4be();
                        break;
                    case \MinecraftNbt\Tag::SHORT:
                        $this->_m_payload = $this->_io->readS2be();
                        break;
                    case \MinecraftNbt\Tag::INT:
                        $this->_m_payload = $this->_io->readS4be();
                        break;
                    case \MinecraftNbt\Tag::BYTE_ARRAY:
                        $this->_m_payload = new \MinecraftNbt\TagByteArray($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::BYTE:
                        $this->_m_payload = $this->_io->readS1();
                        break;
                    case \MinecraftNbt\Tag::INT_ARRAY:
                        $this->_m_payload = new \MinecraftNbt\TagIntArray($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::STRING:
                        $this->_m_payload = new \MinecraftNbt\TagString($this->_io, $this, $this->_root);
                        break;
                    case \MinecraftNbt\Tag::LONG:
                        $this->_m_payload = $this->_io->readS8be();
                        break;
                }
            }
        }
        protected $_m_isTagEnd;
        public function isTagEnd() {
            if ($this->_m_isTagEnd !== null)
                return $this->_m_isTagEnd;
            $this->_m_isTagEnd = $this->type() == \MinecraftNbt\Tag::END;
            return $this->_m_isTagEnd;
        }
        protected $_m_type;
        protected $_m_name;
        protected $_m_payload;
        public function type() { return $this->_m_type; }
        public function name() { return $this->_m_name; }
        public function payload() { return $this->_m_payload; }
    }
}

namespace MinecraftNbt {
    class Tag {

        /**
         * As of KSC 0.9, this enum key causes a syntax error in Lua.
         * See https://github.com/kaitai-io/kaitai_struct/issues/90#issuecomment-766440975
         * for more info.
         */
        const END = 0;
        const BYTE = 1;
        const SHORT = 2;
        const INT = 3;
        const LONG = 4;
        const FLOAT = 5;
        const DOUBLE = 6;
        const BYTE_ARRAY = 7;
        const STRING = 8;
        const LIST = 9;
        const COMPOUND = 10;
        const INT_ARRAY = 11;
        const LONG_ARRAY = 12;
    }
}