PHPackages                             mfonte/fast-toon - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. mfonte/fast-toon

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

mfonte/fast-toon
================

Fastest TOON (Token-Oriented Object Notation) encoder/decoder for PHP 7.0+. 3x faster encoding, 15x faster decoding vs alternatives. LLM-optimized with ~40% token reduction vs JSON.

v1.0.0(4mo ago)03MITPHPPHP ^7.0|^8.0

Since Dec 20Pushed 4mo agoCompare

[ Source](https://github.com/mauriziofonte/fast-php-toon)[ Packagist](https://packagist.org/packages/mfonte/fast-toon)[ Docs](https://github.com/mauriziofonte/fast-php-toon)[ RSS](/packages/mfonte-fast-toon/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (2)Used By (0)

Fast TOON Encoder/Decoder for PHP
=================================

[](#fast-toon-encoderdecoder-for-php)

[![Latest Version on Packagist](https://camo.githubusercontent.com/f8e7f2123936eb0c35d2f3e69556baa0e4a5b539d7f7e5f70c9e503dacfd5b90/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d666f6e74652f666173742d7068702d746f6f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mfonte/fast-php-toon)[![Total Downloads](https://camo.githubusercontent.com/4c89660ad2821b6515c2893c5262c0ebe9f1862296468ece39cc89f7a029cdec/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d666f6e74652f666173742d7068702d746f6f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mfonte/fast-php-toon)[![License](https://camo.githubusercontent.com/c3aee1da813e1ef415bc4664db45692689c4f061876592476b25c6641eb2f955/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d666f6e74652f666173742d7068702d746f6f6e2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mfonte/fast-php-toon)The **fastest** TOON (Token-Oriented Object Notation) encoder and decoder for PHP, with full support for **PHP 7.0 through 8.4**.

TOON is a data serialization format optimized for LLM (Large Language Model) input, providing approximately **40% token reduction** compared to JSON while maintaining full semantic equivalence.

⚡ Performance Highlights
------------------------

[](#-performance-highlights)

This library is specifically optimized for speed and broad compatibility:

Featuremfonte/fast-toonhelgesverre/toon**PHP Version**7.0 - 8.4 ✅8.1+ only**Encoding Speed****3.2x faster**baseline**Decoding Speed****15x faster**baseline**Memory Usage**OptimizedStandard### Benchmark Results

[](#benchmark-results)

Performance comparison against `helgesverre/toon` (the reference implementation):

Data SizeOperationmfonte/fast-toonhelgesverre/toonSpeedupSmall (10 items)Encode9.4 ms27.5 ms**2.9x**Small (10 items)Decode9.2 ms33.5 ms**3.6x**Medium (100 items)Encode85 ms284 ms**3.3x**Medium (100 items)Decode27 ms456 ms**16.9x**Large (1000 items)Encode88 ms274 ms**3.1x**Large (1000 items)Decode24 ms463 ms**19.3x***Benchmarks run on PHP 8.3 with 1000 iterations (100 for large data). Results may vary based on hardware and PHP version.*

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require mfonte/fast-toon
```

Usage
-----

[](#usage)

```
use Mfonte\FastToon\Toon;

$data = [
    'users' => [
        ['id' => 1, 'name' => 'Alice', 'active' => true],
        ['id' => 2, 'name' => 'Bob', 'active' => false],
        ['id' => 3, 'name' => 'Charlie', 'active' => true],
    ]
];

$toon = toon_encode($data);

// Output:
// users[3]{id,name,active}:
// 1|Alice|T
// 2|Bob|F
// 3|Charlie|T

$decoded = toon_decode($toon);
```

### Fluent API

[](#fluent-api)

Instead of using helper functions, you may also use the fluent API:

```
use Mfonte\FastToon\Toon;

$toon = Toon::encode($data)
    ->withFlags(TOON_THROW_ON_ERROR | TOON_KEY_FOLDING)
    ->withDepth(100)
    ->toString();

$decoded = Toon::decode($toon)
    ->withOptions(['strict' => true])
    ->toArray();
```

### Encoding flags

[](#encoding-flags)

Like `json_encode()`, TOON supports bitmask flags for controlling encoding behavior:

```
// Combine flags with bitwise OR
$toon = toon_encode($data, TOON_THROW_ON_ERROR | TOON_KEY_FOLDING);

// Use tab delimiter for tabular output
$toon = toon_encode($data, TOON_TAB_DELIMITER);
```

FlagDescription`TOON_THROW_ON_ERROR`Throw exception instead of returning `false``TOON_FORCE_OBJECT`Force empty/sequential arrays as objects`TOON_PRESERVE_ZERO_FRACTION`Preserve `.0` in floats like `5.0``TOON_TAB_DELIMITER`Use tab as tabular delimiter`TOON_PIPE_DELIMITER`Use pipe as tabular delimiter (default)`TOON_KEY_FOLDING`Enable key folding for nested single-key objects`TOON_INDENT_4`Use 4 spaces for indentation`TOON_NUMERIC_CHECK`Encode numeric strings as numbers`TOON_INVALID_UTF8_IGNORE`Ignore invalid UTF-8 sequences`TOON_INVALID_UTF8_SUBSTITUTE`Substitute invalid UTF-8 with replacement char### Decoding flags

[](#decoding-flags)

```
$data = toon_decode($toon, TOON_STRICT | TOON_THROW_ON_ERROR);
```

FlagDescription`TOON_THROW_ON_ERROR`Throw exception instead of returning `null``TOON_OBJECT_AS_ARRAY`Decode objects as associative arrays`TOON_BIGINT_AS_STRING`Decode big integers as strings`TOON_STRICT`Enable strict mode validation### Error handling

[](#error-handling)

TOON provides error handling similar to JSON:

```
$result = toon_encode($data);

if ($result === false) {
    echo toon_last_error_msg();
}
```

When using `TOON_THROW_ON_ERROR`, exceptions are thrown instead:

```
try {
    $toon = toon_encode($data, TOON_THROW_ON_ERROR);
} catch (\Mfonte\FastToon\Exceptions\EncodingException $e) {
    // Handle exception
}
```

### TOON format overview

[](#toon-format-overview)

TOON uses a line-based syntax that eliminates redundant characters found in JSON.

**Objects** are represented as key-value pairs:

```
name:John Doe
age:30
active:T

```

**Arrays of objects** with the same structure use a highly efficient tabular format:

```
users[3]{id,name,email}:
1|Alice|alice@example.com
2|Bob|bob@example.com
3|Charlie|charlie@example.com

```

This provides approximately 50% token savings compared to the equivalent JSON for tabular data.

Testing
-------

[](#testing)

This package supports PHP 7.0 through 8.4 and provides PHPUnit configurations for each version range.

```
# Run tests on PHP 8.1+ (PHPUnit 10+)
composer test

# Run tests on PHP 7.0-7.1 (PHPUnit 6-7)
composer test:php70

# Run tests on PHP 7.2-8.0 (PHPUnit 8-9)
composer test:php72

# Run tests with coverage
composer test:coverage
```

The test suite is compatible with:

PHPUnit VersionPHP VersionConfig File6.5.14 - 7.5.20PHP 7.0 - 7.1`phpunit-php70.xml.dist`8.5.50 - 9.6.31PHP 7.2 - 8.0`phpunit-php72.xml.dist`10.5.60+PHP 8.1+`phpunit.xml.dist`Code Style
----------

[](#code-style)

This package uses PHP-CS-Fixer for code style enforcement. Two configurations are provided for compatibility across PHP versions.

```
# Check code style (PHP 7.4+, php-cs-fixer 3.x)
composer cs-check

# Fix code style (PHP 7.4+, php-cs-fixer 3.x)
composer cs-fix

# Check code style (PHP 7.0-7.3, php-cs-fixer 2.x)
composer cs-check:v2

# Fix code style (PHP 7.0-7.3, php-cs-fixer 2.x)
composer cs-fix:v2
```

PHP-CS-Fixer VersionPHP VersionConfig File2.19.3PHP 7.0 - 7.3`.php-cs-fixer-v2.php`3.xPHP 7.4+`.php-cs-fixer.dist.php`PHP version compatibility
-------------------------

[](#php-version-compatibility)

This library is designed to work across PHP 7.0 through 8.4:

- **PHP 7.0-7.4**: Full support with polyfills for missing functions
- **PHP 8.0**: Stringable interface support
- **PHP 8.1+**: Enum support, readonly properties

Type support
------------

[](#type-support)

TOON supports all PHP types that `json_encode()` supports:

PHP TypeTOON Representation`null``N``bool``T` / `F``int`Number literal`float`Number literal`string`Unquoted (with escapes)`array` (sequential)Pipe-separated values`array` (associative)Key-value pairs`object`Key-value pairs`JsonSerializable`Via `jsonSerialize()``DateTimeInterface`ISO 8601 string`Enum` (PHP 8.1+)Backed value or name`Stringable` (PHP 8.0+)String conversionBenchmarks
----------

[](#benchmarks)

### TOON vs JSON

[](#toon-vs-json)

Compared to JSON for typical API response data:

MetricJSONTOONImprovementToken Count1000600**40% fewer**Bytes50003800**24% smaller***Token counts measured with OpenAI's tiktoken (cl100k\_base)*

### Running Benchmarks

[](#running-benchmarks)

This library includes comprehensive benchmarks to measure performance:

```
# Compare against helgesverre/toon (requires both libraries installed)
composer benchmark:compare

# Run phpbench microbenchmarks
composer benchmark

# Run phpbench with summary report
composer benchmark:summary

# Run profiling benchmark
composer benchmark:profile
```

The comparative benchmark (`composer benchmark:compare`) will output:

- Encoding/decoding times for small, medium, and large datasets
- Operations per second
- Memory usage
- Speedup factors vs helgesverre/toon

### Why is mfonte/fast-toon faster?

[](#why-is-mfontefast-toon-faster)

Key optimizations that make this library significantly faster:

1. **Inline Type Checks**: Direct type comparisons instead of function calls
2. **Pre-computed Values**: Indent strings, delimiter symbols cached at construction
3. **Optimized String Building**: Direct array appending instead of buffered writing
4. **Fast Path Detection**: Early returns for common primitive types
5. **Minimal Memory Allocation**: Reuse of internal buffers

Why Choose mfonte/fast-toon?
----------------------------

[](#why-choose-mfontefast-toon)

Considerationmfonte/fast-toonhelgesverre/toonPHP 7.0-7.4 support✅ Yes❌ NoPHP 8.0+ support✅ Yes✅ YesEncoding speed⚡ 3x fasterbaselineDecoding speed⚡ 15x fasterbaselineMemory efficiency⚡ OptimizedstandardSpec compliance✅ Full✅ FullChangelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

Credits
-------

[](#credits)

- [Maurizio Fonte](https://github.com/mauriziofonte)
- TOON specification: [github.com/toon-format](https://github.com/toon-format/spec)

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance73

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity39

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

149d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7733524e324e4a6f68d80bad3cfc5737cda0bfb072154210de09c7c2820d070c?d=identicon)[mauriziofonte](/maintainers/mauriziofonte)

---

Top Contributors

[![mauriziofonte](https://avatars.githubusercontent.com/u/1758841?v=4)](https://github.com/mauriziofonte "mauriziofonte (1 commits)")

---

Tags

jsonlaravelcompressionaitokenserializationformatopenaioptimizationfastmachine learningencoderdecoderclaudellmanthropicgptpromptcost-reductiontoon

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/mfonte-fast-toon/health.svg)

```
[![Health](https://phpackages.com/badges/mfonte-fast-toon/health.svg)](https://phpackages.com/packages/mfonte-fast-toon)
```

###  Alternatives

[helgesverre/toon

Token-Oriented Object Notation - A compact data format for reducing token consumption when sending structured data to LLMs

11841.4k9](/packages/helgesverre-toon)[sbsaga/toon

🧠 TOON for Laravel — a compact, human-readable, and token-efficient data format for AI prompts &amp; LLM contexts. Perfect for ChatGPT, Gemini, Claude, Mistral, and OpenAI integrations (JSON ⇄ TOON).

6115.6k](/packages/sbsaga-toon)[vizra/vizra-adk

Vizra Agent Development Kit - A comprehensive Laravel package for building intelligent AI agents.

29026.1k](/packages/vizra-vizra-adk)[claude-php/claude-php-sdk-laravel

Laravel integration for the Claude PHP SDK - Anthropic Claude API

5010.8k](/packages/claude-php-claude-php-sdk-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
