API Reference
Toml (Facade)
The main entry point for all TOML operations.
use PhpCollective\Toml\Toml;decode()
public static function decode(string $input): arrayDecodes a TOML string to a PHP array. Throws ParseException on error.
$config = Toml::decode('[server]\nhost = "localhost"');
// ['server' => ['host' => 'localhost']]decodeFile()
public static function decodeFile(string $path): arrayDecodes a TOML file to a PHP array. Throws ParseException on parse error or unreadable files.
$config = Toml::decodeFile('/path/to/config.toml');parse()
public static function parse(string $input, bool $preserveTrivia = false): DocumentParses a TOML string to an AST Document.
$preserveTrivia: whentrue, attaches leading and trailing trivia to parsed document items and table entries
$document = Toml::parse($tomlString);
foreach ($document->items as $item) {
// Process AST nodes
}tryParse()
public static function tryParse(string $input): ParseResultParses a TOML string without throwing. Returns a ParseResult that may contain errors.
$result = Toml::tryParse($input);
if ($result->isValid()) {
$config = $result->getValue();
} else {
$errors = $result->getErrors();
}Use tryParse() when you need diagnostics and a partial AST instead of exception-driven control flow.
encode()
public static function encode(array $data, ?EncoderOptions $options = null): stringEncodes a PHP array to a TOML string.
$toml = Toml::encode(['key' => 'value']);
// key = "value"encodeDocument()
public static function encodeDocument(Document $document, ?EncoderOptions $options = null): stringEncodes an AST Document to a TOML string.
$document = Toml::parse($original, true);
// Modify document...
$toml = Toml::encodeDocument(
$document,
new EncoderOptions(documentFormatting: DocumentFormattingMode::SourceAware),
);encodeDocument() defaults to normalized output. With DocumentFormattingMode::SourceAware, it can preserve parsed comments, blank lines, lexical styles, and collection-local layout for trivia-preserving ASTs.
ParseResult
Result object from Toml::tryParse().
isValid()
public function isValid(): boolReturns true if parsing succeeded without errors.
getValue()
public function getValue(): ?arrayReturns the parsed array, or null if parsing failed completely.
getDocument()
public function getDocument(): ?DocumentReturns the AST Document. May be available even with errors (partial parse).
getErrors()
public function getErrors(): arrayReturns an array of ParseError objects.
ParseError
Represents a parse error with position information.
Properties
public readonly string $message; // Error description
public readonly Span $span; // Position information
public readonly ?string $hint; // Optional fix suggestionformat()
public function format(string $source): stringFormats the error with source context for display.
echo $error->format($originalToml);
// Parse error: unterminated string
//
// 3 | name = "value
// | ^
// 4 | other = 123
//
// Hint: Did you forget to close the string with "?Span
Position information for tokens and AST nodes.
Properties
public readonly int $start; // 0-based byte offset from start
public readonly int $end; // End byte offset
public readonly int $line; // 1-based line number
public readonly int $column; // 1-based column numberEncoderOptions
Options for TOML encoding.
Constructor
public function __construct(
bool $sortKeys = false,
string $newline = "\n",
DocumentFormattingMode $documentFormatting = DocumentFormattingMode::Normalized,
bool $skipNulls = false,
)$sortKeys: Sort keys alphabetically in output$newline: Newline sequence to use during encoding$documentFormatting:NormalizedorSourceAwareforencodeDocument()$skipNulls: Omitnullvalues duringencode()instead of throwingEncodeException
DocumentFormattingMode
Controls how encodeDocument() emits AST documents.
DocumentFormattingMode::NormalizedProduces normalized TOML output. This is the default.DocumentFormattingMode::SourceAwareReuses preserved source formatting where possible and falls back locally for edited regions.
Null Handling
By default, encode() throws EncodeException for null values. With new EncoderOptions(skipNulls: true), null values are omitted from tables, arrays, and inline tables.
Explicit Encoder Value Types
Use these when you need TOML local temporal literals during encoding instead of quoted strings.
LocalDate
public function __construct(string $value)Encodes as a TOML local date literal like 2024-03-15.
LocalTime
public function __construct(string $value)Encodes as a TOML local time literal like 10:30:45.
LocalDateTime
public function __construct(string $value)Encodes as a TOML local datetime literal like 2024-03-15T10:30:45.
Document
AST root node.
Properties
/** @var array<KeyValue|Table> */
public array $items;Table
AST node for table headers ([name] or [[name]]).
Properties
public Key $key; // Table name
public bool $isArrayTable; // true for [[name]]
/** @var array<KeyValue> */
public array $items; // Key-value pairs in this tableMethods
public function getSpan(): Span;KeyValue
AST node for key-value pairs.
Properties
public Key $key; // The key
public Value $value; // The valueMethods
public function getSpan(): Span;Key
AST node for keys (bare, quoted, or dotted).
Properties
/** @var array<string> */
public array $parts; // Key parts (e.g., ["a", "b"] for "a.b")
/** @var array<KeyStyle> */
public array $styles; // Style for each partKeyStyle
Enum for key styles.
enum KeyStyle: string
{
case Bare = 'bare'; // key
case Basic = 'basic'; // "key"
case Literal = 'literal'; // 'key'
}Value Types
All value nodes implement the Value interface and extend AbstractValue.
Common Methods
public function getValue(): mixed; // Get the PHP value
public function getSpan(): Span; // Get position infoStringValue
public StringStyle $style;StringStyle enum: Basic, Literal, MultiLineBasic, MultiLineLiteral
IntegerValue
public IntegerBase $base;IntegerBase enum: Decimal, Hexadecimal, Octal, Binary
FloatValue
Standard float value.
BoolValue
Boolean value.
OffsetDateTime
DateTime with timezone. getValue() returns DateTimeImmutable.
LocalDateTime
DateTime without timezone. getValue() returns the original string.
LocalDate
Date only. getValue() returns the original string.
LocalTime
Time only. getValue() returns the original string.
ArrayValue
/** @var array<Value> */
public array $items;InlineTable
/** @var array<KeyValue> */
public array $items;Exceptions
ParseException
Thrown when decoding fails or when a TOML file cannot be read.
use PhpCollective\Toml\Exception\ParseException;
try {
Toml::decode($invalid);
} catch (ParseException $e) {
echo $e->getMessage();
}EncodeException
Thrown when encoding fails because a PHP value cannot be represented as TOML.
use PhpCollective\Toml\Exception\EncodeException;
try {
Toml::encode($unsupported);
} catch (EncodeException $e) {
echo $e->getMessage();
}