Leggere file TOML in PHP
In questo articolo vediamo come leggere un file TOML in PHP.
Per farlo useremo yosymfony/toml.
Per l'installazione possiamo usare composer:
composer require yosymfony/toml
Questo il file TOML:
title = "Test TOML"
version = "1.0.0"
[database]
host = "localhost"
port = 5432
username = "root"
password = "password"
databases = ["db_test"]
pool_size = 10
ssl_enabled = true
[server]
host = "0.0.0.0"
port = 8080
debug = false
allowed_hosts = ["*"]
[logging]
level = "INFO"
format = "%(asctime)s - %(levelname)s - %(message)s"
handlers = ["console", "file"]
[cache]
enabled = true
ttl = 3600
max_size = 1000
[features]
enable_api = true
rate_limit = 100
Qui sotto un pò di codice:
require_once 'vendor/autoload.php';
use Yosymfony\Toml\Toml;
try {
$config = Toml::parseFile('test.toml');
echo "Title: " . $config['title'] . "<br>";
echo "Version: " . $config['version'] . "<br>";
echo "Database Host: " . $config['database']['host'] . "<br>";
echo "Database Port: " . $config['database']['port'] . "<br>";
echo "Server Port: " . $config['server']['port'] . "<br>";
echo "Cache Enabled: " . ($config['cache']['enabled'] ? 'true' : 'false') . "<br>";
echo "Databases: " . implode(', ', $config['database']['databases']) . "<br>";
echo "<br>--- Configurazione completa ---<br>";
print_r($config);
echo '<br>';
} catch (Exception $e) {
echo "Errore nella lettura del file TOML: " . $e->getMessage() . "<br>";
}
function getConfig($config, $path, $default = null) {
$keys = explode('.', $path);
$value = $config;
foreach ($keys as $key) {
if (!isset($value[$key])) {
return $default;
}
$value = $value[$key];
}
return $value;
}
echo "Log Level: " . getConfig($config, 'logging.level', 'DEBUG') . "<br>";
echo "Valore inesistente: " . getConfig($config, 'nonexistent.key', 'default_value') . "<br>";
Enjoy!
php composer toml
Commentami!