PHP code example of petalbranch / toml

1. Go to this page and download the library: Download petalbranch/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/ */

    

petalbranch / toml example snippets


use Petalbranch\Toml\Toml;

Toml::enableDetailedErrors(false); // 全局关闭详细错误输出

use Petalbranch\Toml\Parser\Lexer;
use Petalbranch\Toml\Parser\Parser;
use Petalbranch\Toml\Dumper\NodeDumper;
use Petalbranch\Toml\Model\DumperConfig;

$originalToml = <<<TOML
# 数据库核心配置
[database]
server = "192.168.1.1"  # 主库 IP
port = 3306             # 请勿在生产环境修改
TOML;

// 1. 解析为包含完整注释的 AST 树
$parser = new Parser(new Lexer());
$rootNode = $parser->parseToNode($originalToml); 

// 2. 直接修改 AST 节点的值 (自动推断类型)
$rootNode->get('database')->get('port')->setValue(6379);

// 3. 拿着这棵树直接 Dump 出去
$dumper = new NodeDumper(new DumperConfig());
echo $dumper->dump($rootNode);

/* 输出结果:注释被完美保留!
# 数据库核心配置
[database]
server = "192.168.1.1"  # 主库 IP
port = 6379             # 请勿在生产环境修改
*/

use Petalbranch\Toml\Toml;
use Petalbranch\Toml\Model\DumperConfig;

$config = new DumperConfig();
$config->alignEquals = true; // 开启等号对齐

$data = [
    'server' => [
        'ip' => '127.0.0.1',
        'max_connections' => 1000,
        '中文端口号' => 8080,
        'enable' => true
    ]
];

echo Toml::dump($data, $config);

/* 输出极其清爽的排版:
[server]
ip              = "127.0.0.1"
max_connections = 1000
"中文端口号"    = 8080
enable          = true
*/

// 1. 解析 TOML 字符串为 PHP 数组
$tomlString = 'title = "Petalbranch"';
$data = toml_decode($tomlString);

// 2. 将 PHP 数组编码为 TOML 字符串
$config = [
    'server' => [
        'ip' => '127.0.0.1',
        'port' => 8080
    ]
];
echo toml_encode($config);

use Petalbranch\Toml\Toml;

// 解析文件为 PHP 数组
$config = Toml::parseFile(__DIR__ . '/config.toml');

// 直接解析字符串
$tomlString = 'title = "Petalbranch"';
$data = Toml::parse($tomlString);

use Petalbranch\Toml\Toml;
use Petalbranch\Toml\Model\DumperConfig;

$data = [
    'title' => 'TOML Example',
    'owner' => ['name' => 'Tom', 'dob' => new \DateTime('1979-05-27T07:32:00-08:00')]
];

// 使用默认配置生成字符串
$toml = Toml::dump($data);

// 使用自定义配置并直接写入文件
$config = new DumperConfig();
$config->inlineTable = true; // 开启内联表智能压缩
Toml::dumpFile(__DIR__ . '/config.generated.toml', $data, $config);

use Petalbranch\Toml\Toml;

$cacheFile = __DIR__ . '/runtime/toml_cache.php';

if (is_file($cacheFile) && !constant('DEBUG_MODE')) {
    $config = ';');
}
text
> cd tests && .\toml-test-v2.1.0-windows-amd64.exe test -toml "1.1" -decoder "php toml-test-decoder.php" -encoder "php toml-test-encoder.php"

toml-test v2.1.0
  valid tests:   214 passed, 0 failed
  encoder tests: 213 passed, 1 failed
  invalid tests: 466 passed, 0 failed