PHPackages                             phpiando/toonify - 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. phpiando/toonify

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

phpiando/toonify
================

A PHP library to convert between JSON and TOON format for optimized LLM data exchange.

1.0.0(6mo ago)01MITPHPPHP ^8.3

Since Nov 10Pushed 6mo agoCompare

[ Source](https://github.com/phpiando/toonify)[ Packagist](https://packagist.org/packages/phpiando/toonify)[ RSS](/packages/phpiando-toonify/feed)WikiDiscussions main Synced 1mo ago

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

🎒 toonify
=========

[](#-toonify)

PHP library for conversion between JSON and TOON (Token-Oriented Object Notation) - an optimized format for saving tokens in Large Language Models (LLMs).

[![PHP Version](https://camo.githubusercontent.com/91e2ff786d2fba1edf015025006e0156a071320b3662eaf2c50f39d4bb4b2369/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e332d626c7565)](https://www.php.net/)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)

☕ Sponsors
----------

[](#-sponsors)

If you find this plugin useful, consider sponsoring its development:

- [Sponsor on GitHub](https://github.com/sponsors/phpiando)

📖 What is TOON?
---------------

[](#-what-is-toon)

TOON (Token-Oriented Object Notation) is a compact and readable serialization format, specifically designed to reduce token usage when sending structured data to LLMs. It can save **30-60% of tokens** compared to JSON.

### Why use TOON?

[](#why-use-toon)

- 💸 **Token savings**: 30-60% fewer tokens than JSON
- 🤖 **Optimized for LLMs**: Better understanding and accuracy
- 📊 **Perfect for tabular data**: Uniform arrays of objects
- 🔄 **Lossless conversion**: Converts to and from JSON without data loss

### Quick Comparison

[](#quick-comparison)

**JSON (123 tokens):**

```
{
  "title": "Employees",
  "total": 3,
  "data": [
    {
      "id": 1,
      "name": "Roni",
      "email": "roni@phpiando.com"
    },
    {
      "id": 2,
      "name": "Sommerfeld",
      "email": "sommerfeld@phpiando.com"
    },
    {
      "id": 3,
      "name": "PHPiando",
      "email": "phpiando@phpiando.com"
    }
  ]
}
```

**TOON (64 tokens - 48% savings):**

```
title: Employees
total: 3
data[3]{id,name,email}:
  1,Roni,roni@phpiando.com
  2,Sommerfeld,sommerfeld@phpiando.com
  3,PHPiando,phpiando@phpiando.com

```

🚀 Installation
--------------

[](#-installation)

```
composer require phpiando/toonify
```

### Requirements

[](#requirements)

- PHP 8.3 or higher
- ext-json
- ext-mbstring

📚 Basic Usage
-------------

[](#-basic-usage)

### Simple Conversion

[](#simple-conversion)

```
use Toonify\Toon;

// PHP Array to TOON
$data = [
  'title' => 'Employees',
  'total' => 3,
  'data' => [
    ['id' => 1, 'name' => 'Roni', 'email' => 'roni@phpiando.com'],
    ['id' => 2, 'name' => 'Sommerfeld', 'email' => 'sommerfeld@phpiando.com'],
    ['id' => 3, 'name' => 'PHPiando', 'email' => 'phpiando@phpiando.com'],
  ]
];

$toon = Toonify::encode($data);
echo $toon;
// title: Employees
// total: 3
// data[3]{id,name,email}:
//   1,Roni,roni@phpiando.com
//   2,Sommerfeld,sommerfeld@phpiando.com
//   3,PHPiando,phpiando@phpiando.com

// TOON to PHP Array
$decoded = Toonify::decode($toon);
```

### From JSON String

[](#from-json-string)

```
$json = '{"name": "Roni Sommerfeld", "age": 37}';
$toon = Toonify::fromJsonString($json);

$jsonBack = Toonify::toJsonString($toon);
```

### From Local Files

[](#from-local-files)

```
// JSON → TOON
$toon = Toonify::fromJsonDisk('/path/to/data.json');
file_put_contents('/path/to/output.toon', $toon);

// TOON → JSON
$json = Toonify::toJsonDisk('/path/to/data.toon');
file_put_contents('/path/to/output.json', $json);
```

### From URLs

[](#from-urls)

```
// Fetch JSON from URL and convert to TOON
$toon = Toonify::fromJsonUrl('https://api.example.com/data.json');

// Fetch TOON from URL and convert to JSON
$json = Toonify::toJsonUrl('https://example.com/data.toon');
```

### Extract TOON from Markdown (LLM Responses)

[](#extract-toon-from-markdown-llm-responses)

A special feature for working with LLM responses that frequently return data in markdown blocks:

```
$llmResponse =  '',    // Length prefix (optional)
]);

```

**Delimiter examples:**

```
// Comma (default)
$toon = Toonify::encode($data, ['delimiter' => ',']);
// users[2,]{id,name}:

// Tab (more token efficient)
$toon = Toonify::encode($data, ['delimiter' => "\t"]);
// users[2	]{id,name}:

// Pipe
$toon = Toonify::encode($data, ['delimiter' => '|']);
// users[2|]{id,name}:
```

### Decoding Options

[](#decoding-options)

```
$data = Toonify::decode($toon, [
  'strict' => true,        // Strict validation (default: true)
  'indent' => 2,           // Expected spaces per level
]);
```

📋 Supported Formats
-------------------

[](#-supported-formats)

### Simple Objects

[](#simple-objects)

```
['name' => 'Roni Sommerfeld', 'age' => 37]
```

```
name: Roni Sommerfeld
age: 37

```

### Primitive Arrays

[](#primitive-arrays)

```
[1, 2, 3, 4, 5]
```

```
[5,]: 1,2,3,4,5

```

### Tabular Arrays (Sweet Spot!)

[](#tabular-arrays-sweet-spot)

```
[
  ['id' => 1, 'name' => 'Roni'],
  ['id' => 2, 'name' => 'PHPiando']
]
```

```
[2,]{id,name}:
  1,Roni
  2,PHPiando

```

### Mixed Arrays

[](#mixed-arrays)

```
[
  ['x' => 1],
  42,
  'hello'
]
```

```
[3,]:
  - x: 1
  - 42
  - hello

```

🎯 Use Cases
-----------

[](#-use-cases)

### 1. Send data to LLMs

[](#1-send-data-to-llms)

```
$repositories = fetchGitHubRepos();
$toon = Toonify::encode($repositories, ['delimiter' => "\t"]);

// Save tokens in prompt
$prompt = "Analyze these repositories:\n\n" . $toon;
$response = $llm->complete($prompt);
```

### 2. Process LLM responses

[](#2-process-llm-responses)

```
$response = $llm->complete("List 5 products in TOON format");
$toon = Toonify::extractFromMarkdown($response);
$products = Toonify::decode($toon);
```

### 3. Optimized APIs

[](#3-optimized-apis)

```
// Endpoint that returns TOON instead of JSON
header('Content-Type: text/plain');
$data = $database->query('SELECT * FROM users');
echo Toonify::encode($data);
```

### 4. Compact logs

[](#4-compact-logs)

```
$logData = [
  'timestamp' => time(),
  'events' => $events
];
file_put_contents('log.toon', Toonify::encode($logData));
```

🧪 Testing
---------

[](#-testing)

```
composer test
```

📊 Benchmarks
------------

[](#-benchmarks)

Run examples to see token savings:

```
php examples/basic.php
```

Typical results:

- Simple objects: ~20-30% savings
- Tabular arrays: ~40-60% savings
- Mixed arrays: ~25-35% savings

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please:

1. Fork the project
2. Create a feature branch (`git checkout -b feature/MyFeature`)
3. Commit your changes (`git commit -am 'Add new feature'`)
4. Push to the branch (`git push origin feature/MyFeature`)
5. Open a Pull Request

📄 License
---------

[](#-license)

This project is under the MIT license. See the [LICENSE](LICENSE) file for more details.

🔗 Useful Links
--------------

[](#-useful-links)

- [Official TOON specification](https://github.com/toon-format/spec)
- [Reference TypeScript implementation](https://github.com/toon-format/toon)
- [Online playground](https://jsontoon.net/)

🙏 Credits
---------

[](#-credits)

TOON was created by [Johann Schopplich](https://github.com/johannschopplich).

This PHP library is an implementation of the official TOON v1.3 specification.

💬 Support
---------

[](#-support)

- 🐛 Issues: [GitHub Issues](https://github.com/phpiando/toonify/issues)
- 💡 Discussions: [GitHub Discussions](https://github.com/phpiando/toonify/discussions)

---

Made with ❤️ for the PHP community

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance68

Regular maintenance activity

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 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

187d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b291319098f6d745cd7e7edcf533b72820e5b4114c9b8ab6003a51dc94b61bfe?d=identicon)[phpiando](/maintainers/phpiando)

---

Top Contributors

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

---

Tags

jsonaiserializationllmtoontoken-optimization

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/phpiando-toonify/health.svg)

```
[![Health](https://phpackages.com/badges/phpiando-toonify/health.svg)](https://phpackages.com/packages/phpiando-toonify)
```

###  Alternatives

[jms/serializer

Library for (de-)serializing data of any complexity; supports XML, and JSON.

2.3k135.8M851](/packages/jms-serializer)[jms/serializer-bundle

Allows you to easily serialize, and deserialize data of any complexity

1.8k89.3M627](/packages/jms-serializer-bundle)[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)[mischasigtermans/laravel-toon

Token-Optimized Object Notation encoder/decoder for Laravel with intelligent nested object handling

13113.1k](/packages/mischasigtermans-laravel-toon)[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)

PHPackages © 2026

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