PHP Logosymfony/yaml

The `symfony/yaml` component is a powerful PHP library provided by the Symfony project that allows developers to parse YAML (YAML Ain't Markup Language) strings and files into PHP arrays or objects, and conversely, to dump PHP arrays or objects into YAML formatted strings. YAML is a human-friendly data serialization standard often used for configuration files, data exchange, and writing task specifications due to its readability and simplicity compared to XML or even JSON for certain use cases.

Key features and uses of `symfony/yaml`:
1. Parsing YAML: It can take a YAML string or the content of a YAML file and convert it into a native PHP data structure (associative arrays and scalar values). This is typically done using the `Yaml::parse()` method.
2. Dumping PHP to YAML: It can convert a PHP array or object into a well-formatted YAML string, making it easy to generate configuration files or other data in YAML format. The `Yaml::dump()` method is used for this.
3. Error Handling: The component provides robust error handling, throwing `Symfony\Component\Yaml\Exception\ParseException` for malformed YAML syntax, which helps in debugging and ensuring data integrity.
4. YAML Specification Support: It adheres to the YAML 1.2 specification, supporting various data types including strings, integers, floats, booleans, arrays (sequences), and associative arrays (mappings).
5. Inline Level and Indentation: When dumping YAML, you can control the inline level (how many levels of nested data are kept on a single line) and the indentation size, allowing for flexible output formatting.
6. Integration: While being a core component of the Symfony framework for managing configurations, it's designed to be a standalone library and can be easily integrated into any PHP project via Composer.

Example Code

<?php

require 'vendor/autoload.php';

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

// --- Example 1: Parsing a YAML string ---
echo "--- Parsing YAML String ---\n";
$yamlString = <<<YAML
parameters:
    database_host: localhost
    database_port: 3306
    database_name: my_app
    debug: true
    users:
        - name: Alice
          email: alice@example.com
        - name: Bob
          email: bob@example.com
YAML;

try {
    $parsedData = Yaml::parse($yamlString);
    echo "Parsed Data (from string):\n";
    print_r($parsedData);
} catch (ParseException $exception) {
    printf('Unable to parse the YAML string: %s', $exception->getMessage());
}

echo "\n";

// --- Example 2: Parsing a YAML file ---
echo "--- Parsing YAML File ---\n";
// Create a dummy YAML file for demonstration
$yamlFileContent = <<<YAML
app:
    name: My Awesome App
    version: 1.0.0
    settings:
        log_level: info
        cache_enabled: true
services:
    userService:
        class: App\\Service\\UserService
        arguments: ['@database_connection']
YAML;

file_put_contents('config.yaml', $yamlFileContent);

try {
    $parsedFileData = Yaml::parseFile('config.yaml');
    echo "Parsed Data (from config.yaml):\n";
    print_r($parsedFileData);
} catch (ParseException $exception) {
    printf('Unable to parse the YAML file: %s', $exception->getMessage());
} finally {
    // Clean up the dummy file
    if (file_exists('config.yaml')) {
        unlink('config.yaml');
    }
}

echo "\n";

// --- Example 3: Dumping a PHP array to a YAML string ---
echo "--- Dumping PHP Array to YAML String ---\n";
$phpArray = [
    'product' => [
        'id' => 123,
        'name' => 'Widget A',
        'price' => 19.99,
        'available' => true,
        'tags' => ['electronics', 'gadget'],
        'details' => [
            'weight' => '1.5kg',
            'color' => 'black'
        ]
    ],
    'environment' => 'development'
];

// Dump with default settings
$dumpedYamlDefault = Yaml::dump($phpArray);
echo "Dumped YAML (default):\n";
echo $dumpedYamlDefault;

echo "\n";

// Dump with a specific inline level (e.g., 2) and indentation (e.g., 4 spaces)
$dumpedYamlCustom = Yaml::dump($phpArray, 2, 4);
echo "Dumped YAML (inline level 2, indent 4):\n";
echo $dumpedYamlCustom;

echo "\n";

// Dump with Yaml::DUMP_OBJECT_AS_MAP for objects (if you pass an object instead of array)
// For this example, we'll stick to arrays for simplicity but mention the flag.
// If $phpArray was an object, this flag would make it dump as a map instead of a serialized object string.
$dumpedYamlObjectAsMap = Yaml::dump($phpArray, 2, 4, Yaml::DUMP_OBJECT_AS_MAP);
echo "Dumped YAML (with DUMP_OBJECT_AS_MAP):\n";
echo $dumpedYamlObjectAsMap;

?>