Skip to content

Encoding

PHP Toml encodes PHP arrays to TOML and supports explicit value wrappers for TOML local date/time/datetime literals.

Basic Encoding

php
use PhpCollective\Toml\Toml;

$toml = Toml::encode([
    'title' => 'My App',
    'database' => [
        'host' => 'localhost',
        'port' => 5432,
    ],
]);

Output:

toml
title = "My App"

[database]
host = "localhost"
port = 5432

Supported Input Types

PHP TypeTOML Output
stringBasic string "value"
intInteger 42
floatFloat 3.14
boolBoolean true / false
array (list)Array [1, 2, 3]
array (assoc)Table or inline table depending on position
DateTimeInterfaceOffset datetime
PhpCollective\Toml\Value\LocalDateLocal date
PhpCollective\Toml\Value\LocalTimeLocal time
PhpCollective\Toml\Value\LocalDateTimeLocal datetime

null is not supported and throws EncodeException.

Encoder Options

php
use PhpCollective\Toml\Encoder\EncoderOptions;

$options = new EncoderOptions(
    sortKeys: true,
    newline: "\n",
);

$toml = Toml::encode($data, $options);

Sort Keys

php
$toml = Toml::encode([
    'zebra' => 1,
    'apple' => 2,
    'mango' => 3,
], new EncoderOptions(sortKeys: true));

Output:

toml
apple = 2
mango = 3
zebra = 1

Custom Newlines

php
$toml = Toml::encode([
    'name' => 'test',
    'count' => 42,
], new EncoderOptions(newline: "\r\n"));

Skip Null Values

By default, null values throw EncodeException. Use skipNulls to silently omit them:

php
$toml = Toml::encode([
    'name' => 'Alice',
    'email' => null,  // Will be omitted
    'age' => 30,
], new EncoderOptions(skipNulls: true));

Output:

toml
name = "Alice"
age = 30

This also filters nulls from arrays and inline tables.

Date and Time Encoding

Offset Datetime

Use DateTimeInterface for TOML offset datetimes:

php
$toml = Toml::encode([
    'created' => new DateTimeImmutable('2024-01-15T10:30:00Z'),
]);

Output:

toml
created = 2024-01-15T10:30:00.000000+00:00

Local Date, Time, and DateTime

Use explicit wrappers for TOML local temporal values:

php
use PhpCollective\Toml\Value\LocalDate;
use PhpCollective\Toml\Value\LocalDateTime;
use PhpCollective\Toml\Value\LocalTime;

$toml = Toml::encode([
    'date' => new LocalDate('2024-03-15'),
    'time' => new LocalTime('10:30:45'),
    'timestamp' => new LocalDateTime('2024-03-15T10:30:45'),
]);

Output:

toml
date = 2024-03-15
time = 10:30:45
timestamp = 2024-03-15T10:30:45

Plain PHP strings are always encoded as TOML strings, not temporal literals.

Array of Tables

Sequential arrays of associative arrays become array-of-tables:

php
$toml = Toml::encode([
    'servers' => [
        ['name' => 'alpha', 'ip' => '10.0.0.1'],
        ['name' => 'beta', 'ip' => '10.0.0.2'],
    ],
]);

Output:

toml
[[servers]]
name = "alpha"
ip = "10.0.0.1"

[[servers]]
name = "beta"
ip = "10.0.0.2"

Special Float Values

php
$toml = Toml::encode([
    'infinity' => INF,
    'negative_infinity' => -INF,
    'not_a_number' => NAN,
]);

Output:

toml
infinity = inf
negative_infinity = -inf
not_a_number = nan

String Escaping

Strings are emitted as basic strings with escapes:

php
$toml = Toml::encode([
    'message' => "Hello\nWorld",
    'path' => 'C:\Users\name',
]);

Output:

toml
message = "Hello\nWorld"
path = "C:\\Users\\name"

Re-encoding from AST

php
$document = Toml::parse($originalToml, true);

// Modify the AST...

$toml = Toml::encodeDocument(
    $document,
    new EncoderOptions(documentFormatting: DocumentFormattingMode::SourceAware),
);

WARNING

encodeDocument() defaults to normalized output. Use DocumentFormattingMode::SourceAware when you want minimal-diff, source-aware behavior for trivia-preserving ASTs.

In SourceAware mode, unchanged parsed regions can round-trip losslessly and edited regions follow local fallback rules. Compatible key, value, dotted-key, and table-header edits can often keep their original separator spacing, and single-line collections preserve local delimiter style when the AST has consistent local formatting evidence. If not, the encoder canonicalizes locally.

For the full editing contract and compatibility boundary, see Compatibility.

Error Handling

Encoding throws EncodeException for unsupported values:

php
use PhpCollective\Toml\Exception\EncodeException;

try {
    $toml = Toml::encode([
        'callback' => fn() => 'hello',
    ]);
} catch (EncodeException $e) {
    echo $e->getMessage();
}

Common unsupported values:

  • null
  • closures
  • resources
  • arbitrary objects that do not implement the TOML value contract
  • circular references

Released under the MIT License.