symfony/yaml
Symfony Yaml component for parsing, loading, and dumping YAML documents in PHP. Supports reading YAML files/strings and exporting arrays/objects to YAML with configurable formatting, inline levels, and error handling. Includes comprehensive docs and Symfony integration.
Install via Composer:
composer require symfony/yaml
use Symfony\Component\Yaml\Yaml;
// Load a YAML file into a PHP array
$config = Yaml::parseFile(__DIR__.'/config.yaml');
// Or parse a YAML string directly
$yamlString = "name: John\nage: 30";
$data = Yaml::parse($yamlString);
$data = [
'name' => 'John',
'age' => 30,
'skills' => ['PHP', 'Laravel']
];
// Dump to a YAML string
$yamlString = Yaml::dump($data);
// Save to a file
Yaml::dumpFile(__DIR__.'/output.yaml', $data);
Symfony\Component\Yaml\Yaml (main facade), Parser, DumperYaml::DUMP_OBJECT_AS_ARRAY, Yaml::DUMP_NULL_AS_EMPTY, etc.// config/app.yaml
database:
default: mysql
connections:
mysql:
driver: pdo_mysql
host: localhost
database: app_db
// In Laravel service provider
public function boot()
{
$config = Yaml::parseFile(config_path('app.yaml'));
$this->app->singleton('config', fn() => $config);
}
// Generate YAML for API responses
$responseData = [
'status' => 'success',
'data' => [
'user' => [
'id' => 1,
'name' => 'Jane Doe',
'roles' => ['admin', 'user']
]
]
];
$yamlResponse = Yaml::dump($responseData, 10, 2); // Indent 10, inline arrays after 2 items
// Merge base and environment-specific configs
$baseConfig = Yaml::parseFile(config_path('base.yaml'));
$envConfig = Yaml::parseFile(config_path('local.yaml'));
$mergedConfig = array_merge_recursive($baseConfig, $envConfig);
// Validate against a schema (using Symfony's Validator)
$validator = $this->container->get('validator');
$constraints = Yaml::parseFile(config_path('validation_schema.yaml'));
$errors = $validator->validate($data, $constraints);
use Illuminate\Support\Facades\Storage;
// Load YAML from storage
$yamlContent = Storage::disk('config')->get('services.yaml');
$services = Yaml::parse($yamlContent);
// Save YAML to storage
Storage::disk('logs')->put('error_log.yaml', Yaml::dump($errors));
// Register YAML-based configuration
public function register()
{
$this->mergeConfigFrom(
Yaml::parseFile(__DIR__.'/configs/database.yaml'),
'database.connections'
);
}
// Use YAML for command configuration
protected function getConfig()
{
return Yaml::parseFile(__DIR__.'/config.yaml');
}
// Publish YAML templates
public function boot()
{
$this->publishes([
__DIR__.'/configs/default.yaml' => config_path('vendor/packages/default.yaml'),
], 'package-config');
}
// Test YAML parsing in PHPUnit
public function testYamlParsing()
{
$yaml = <<<'YAML'
name: Test User
roles:
- admin
- editor
YAML;
$data = Yaml::parse($yaml);
$this->assertEquals('Test User', $data['name']);
$this->assertContains('admin', $data['roles']);
}
Yaml::parse($yaml, null, Yaml::PARSE_CONSTRAINED) to enforce strict parsing or handle duplicates in your code:
$data = Yaml::parse($yaml);
$data = array_unique($data, SORT_REGULAR); // Simple deduplication
!!binary) must be stringable. Non-stringables will throw an error.$binaryData = file_get_contents('image.png');
$data['image'] = base64_encode($binaryData); // Store as base64 string
Yaml::DUMP_EMPTY_ARRAY_AS_EMPTY or increase PHP's xdebug.max_nesting_level if needed."...") or literal blocks (|) for multiline content:
# Correct
description: |
This is a
multiline string.
DateTime objects.$data['created_at'] = new DateTime($data['created_at']);
Yaml::parse($yaml, null, Yaml::PARSE_CONSTRAINED);
This will throw exceptions for invalid YAML, making debugging easier.
$data = Yaml::parse($yaml);
dump($data); // Use Laravel's dump() or Symfony's VarDumper
$cleanYaml = preg_replace('/[\x00-\x1F]/', '', $yaml);
Yaml::DUMP_OBJECT_AS_ARRAY: Converts objects to arrays during dumping.Yaml::DUMP_NULL_AS_EMPTY: Omits null values entirely.Yaml::DUMP_EMPTY_ARRAY_AS_EMPTY: Omits empty arrays.Yaml::DUMP_FORCE_DOUBLE_QUOTES_ON_VALUES: Ensures all strings are double-quoted.Example:
$yaml = Yaml::dump($data, 10, 2, Yaml::DUMP_OBJECT_AS_ARRAY | Yaml::DUMP_NULL_AS_EMPTY);
Yaml::addTagHandler('!my_tag', function ($value) {
return new MyCustomClass($value);
});
$parser = new Parser();
$data = $parser->parse(new StringStream($yaml));
Extend Symfony\Component\Yaml\Dumper to add custom formatting:
class CustomDumper extends Dumper
{
protected function serializeScalar($value, $inline, $depth)
{
if ($value instanceof MyCustomClass) {
return $this->representScalar('!my_tag', $value->getId());
}
return parent::serializeScalar($value, $inline, $depth);
}
}
Wrap Yaml::parse() and Yaml::dump() for consistency:
function parseYaml($yaml, array $options = [])
{
$data = Yaml::parse($yaml, null, Yaml::PARSE_CONSTRAINED);
return postProcessData($data);
}
function dumpYaml($data, array $options = [])
{
return Yaml::dump(preProcessData($data), 10, 2, $options);
}
Create a
How can I help you explore Laravel packages today?