Working with YAML in PHP: Symfony Yaml Library and Data Parsing

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with YAML in PHP: Symfony Yaml Library



YAML (YAML Ain't Markup Language) is a data serialization format often used for configuration files, describing data structures, and exchanging information between services. In PHP, there are several solutions for working with YAML, but the most popular and functional is the Symfony Yaml component. It provides convenient methods for parsing (reading) and dumping (writing) YAML data, supports all YAML 1.2 specifications, and is built into many frameworks, including Laravel and Symfony.



In this article, we will thoroughly cover installation, basic operations, and advanced features of the Symfony Yaml library. You will learn how to convert YAML to PHP arrays and back, as well as how to handle complex structures.



Installing the Library



Symfony Yaml is installed via Composer. Run the command in the root of your project:



composer require symfony/yaml


After installation, include the Composer autoloader and import the necessary classes:



require 'vendor/autoload.php';

use Symfony\\Component\\Yaml\\Yaml;use Symfony\\Component\\Yaml\\Exception\\ParseException;


Basic Operations



Parsing a YAML String



The Yaml::parse() method converts a YAML string into a PHP array. Let's look at an example with a simple configuration:



$yamlString = "database:    host: localhost    port: 3306    name: mydb    user: admin    password: secret";

try { $data = Yaml::parse($yamlString); print_r($data);} catch (ParseException $e) { echo 'YAML parsing error: ' . $e->getMessage();}


Result:



Array(    [database] => Array        (            [host] => localhost            [port] => 3306            [name] => mydb            [user] => admin            [password] => secret        ))


Parsing a YAML File



More often, YAML is stored in files. To read them, use file_get_contents() together with the parser:



$yamlFile = __DIR__ . '/config.yaml';if (!file_exists($yamlFile)) {    die('Configuration file not found');}

try { $config = Yaml::parse(file_get_contents($yamlFile)); echo 'Database host: ' . $config['database']['host'];} catch (ParseException $e) { echo 'File reading error: ' . $e->getMessage();}


Dumping (Writing) to YAML



The Yaml::dump() method converts a PHP array back into a YAML string. This is useful for generating configurations or exporting data:



$data = [    'app' => [        'name' => 'MyApp',        'version' => '1.0.0',        'debug' => true,        'modules' => ['auth', 'api', 'admin']    ]];

$yamlOutput = Yaml::dump($data, 3); // Second parameter — nesting levelfile_put_contents('app_config.yaml', $yamlOutput);echo $yamlOutput;


Result in the file:



app:    name: MyApp    version: '1.0.0'    debug: true    modules:        - auth        - api        - admin


Advanced Features



Handling Nested Structures and Special Types



Symfony Yaml supports nesting of any depth, as well as special data types such as dates, null, and boolean values:



$complexYaml = "server:    host: 192.168.1.1    ports:        - 80        - 443        - 8080    settings:        timeout: 30        enabled: true        description: ~        created_at: 2024-01-15";

$parsed = Yaml::parse($complexYaml);var_dump($parsed['server']['settings']['enabled']); // bool(true)var_dump($parsed['server']['settings']['description']); // NULLvar_dump($parsed['server']['settings']['created_at']); // string(10) "2024-01-15"


Custom Parsing Flags

\

Recommendations