Toon provides three encoding methods and a flexible options object for controlling output.
Standard encoding with configurable options.
use JayI\Toon\Toon;
use JayI\Toon\Encoding\EncoderOptions;
use JayI\Toon\Enums\Delimiter;
$toon = Toon::encode($data);
$toon = Toon::encode($data, new EncoderOptions(indentSize: 4));
$toon = Toon::encode($data, new EncoderOptions(delimiter: Delimiter::Pipe));Encodes with settings optimized for maximum token savings: 1-space indent and key folding enabled.
$toon = Toon::compact([
'data' => ['meta' => ['items' => ['x', 'y']]],
]);
// Output: data.meta.items[2]: x,yAutomatically chooses compact or default encoding based on the data structure. Uses compact when it detects foldable nested chains or deep nesting (depth >= 4); uses default otherwise.
$toon = Toon::smart($data); // compact for foldable/deep data, default otherwiseAll options are passed via the EncoderOptions value object:
use JayI\Toon\Encoding\EncoderOptions;
$options = new EncoderOptions(
indentSize: 2,
delimiter: Delimiter::Comma,
keyFolding: KeyFolding::Off,
flattenDepth: INF,
);| Option | Default | Description |
|---|---|---|
indentSize |
2 |
Spaces per indentation level |
delimiter |
Comma |
Value separator: Comma, Tab, or Pipe |
keyFolding |
Off |
Off or Safe. When Safe, collapses single-key chains to dotted paths |
flattenDepth |
INF |
Max segments to fold when key folding is enabled |
EncoderOptions::compact(); // indentSize=1, keyFolding=SafeThe encoder automatically normalizes common PHP types before encoding:
DateTime/DateTimeImmutable/Carboninstances are converted to ISO 8601 strings- Backed enums are converted to their value
- Unit enums are converted to their name
- Objects implementing
JsonSerializableare serialized viajsonSerialize() Stringableobjects are cast to stringTraversableobjects are iterated into arrays- Other objects are cast to arrays of their properties (an empty
stdClassencodes as an empty object) - Non-finite floats (
NAN,INF) becomenull,-0.0becomes0, and integral floats become integers
Estimate how much TOON saves compared to JSON:
$stats = Toon::savings($data);
// [
// 'json_chars' => 238,
// 'toon_chars' => 150,
// 'saved_chars' => 88,
// 'saved_percent' => 37.0,
// ]
// Compare with compact encoding
$stats = Toon::savings($data, EncoderOptions::compact());