PHP code example of php-collective / toml

1. Go to this page and download the library: Download php-collective/toml library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

php-collective / toml example snippets


use PhpCollective\Toml\Toml;
use PhpCollective\Toml\TomlVersion;

// Decode TOML to PHP array
$config = Toml::decode(<<<'TOML'
[database]
host = "localhost"
port = 5432
TOML);

echo $config['database']['host']; // "localhost"

// Opt into strict TOML 1.0 parsing/decoding
$strict = Toml::decode('time = 07:32:00', TomlVersion::V10);

// Encode PHP array to TOML
$toml = Toml::encode([
    'server' => [
        'host' => '0.0.0.0',
        'port' => 8080,
    ],
]);

// Decode string - throws ParseException on error
$array = Toml::decode($tomlString);

// Decode file
$array = Toml::decodeFile('/path/to/config.toml');

// Parse without throwing - for tooling
$result = Toml::tryParse($tomlString);
if ($result->isValid()) {
    $array = $result->getValue();
} else {
    foreach ($result->getErrors() as $error) {
        echo $error->format($tomlString);
    }
}

// Parse to AST for analysis
$document = Toml::parse($tomlString);

// Parse without exceptions and keep diagnostics + partial AST
$result = Toml::tryParse($tomlString);
$document = $result->getDocument();

use PhpCollective\Toml\Encoder\DocumentFormattingMode;
use PhpCollective\Toml\Encoder\EncoderOptions;
use PhpCollective\Toml\Ast\Value\StringStyle;
use PhpCollective\Toml\Ast\Value\StringValue;
use PhpCollective\Toml\TomlVersion;

// Encode to TOML string
$toml = Toml::encode($array);

// Encode directly to file
Toml::encodeFile('/path/to/config.toml', $array);

// With options - e.g. omit nulls instead of throwing
$toml = Toml::encode($array, new EncoderOptions(skipNulls: true));

// Strict TOML 1.0 output
$toml = Toml::encode($array, new EncoderOptions(version: TomlVersion::V10));

// encodeDocument() is normalized by default
$document = Toml::parse($tomlString, true);
$toml = Toml::encodeDocument($document);

// Encode document directly to file
Toml::encodeDocumentFile('/path/to/output.toml', $document);

// Opt into source-aware formatting for minimal-diff AST re-encoding
$document = Toml::parse($tomlString, true);
$document->items[0]->value = new StringValue('new value');
$toml = Toml::encodeDocument(
    $document,
    new EncoderOptions(documentFormatting: DocumentFormattingMode::SourceAware),
);

$result = Toml::tryParse($input);
foreach ($result->getErrors() as $error) {
    // $error->message - Error description
    // $error->span    - Position (line, column, offset)
    // $error->hint    - Optional suggestion
}
bash
composer