Skip to content

The Yaml Component

Warning: You are browsing the documentation for Symfony 2.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.1 (the current stable version).

The Yaml component loads and dumps YAML files.

What is It?

The Symfony Yaml component parses YAML strings to convert them to PHP arrays. It is also able to convert PHP arrays to YAML strings.

YAML, YAML Ain't Markup Language, is a human friendly data serialization standard for all programming languages. YAML is a great format for your configuration files. YAML files are as expressive as XML files and as readable as INI files.

The Symfony Yaml Component implements a selected subset of features defined in the YAML 1.2 version specification.

Tip

Learn more about the Yaml component in the The YAML Format article.

Installation

1
$ composer require symfony/yaml

Alternatively, you can clone the https://github.com/symfony/yaml repository.

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Why?

Fast

One of the goals of Symfony Yaml is to find the right balance between speed and features. It supports just the needed features to handle configuration files. Notable lacking features are: document directives, multi-line quoted messages, compact block collections and multi-document files.

Real Parser

It sports a real parser and is able to parse a large subset of the YAML specification, for all your configuration needs. It also means that the parser is pretty robust, easy to understand, and simple enough to extend.

Clear Error Messages

Whenever you have a syntax problem with your YAML files, the library outputs a helpful message with the filename and the line number where the problem occurred. It eases the debugging a lot.

Dump Support

It is also able to dump PHP arrays to YAML with object support, and inline level configuration for pretty outputs.

Types Support

It supports most of the YAML built-in types like dates, integers, octals, booleans, and much more...

Full Merge Key Support

Full support for references, aliases, and full merge key. Don't repeat yourself by referencing common configuration bits.

Using the Symfony YAML Component

The Symfony Yaml component is very simple and consists of two main classes: one parses YAML strings (Parser), and the other dumps a PHP array to a YAML string (Dumper).

On top of these two classes, the Yaml class acts as a thin wrapper that simplifies common uses.

Reading YAML Files

The parse() method parses a YAML string and converts it to a PHP array:

1
2
3
use Symfony\Component\Yaml\Yaml;

$value = Yaml::parse(file_get_contents('/path/to/file.yml'));

Caution

Because it is currently possible to pass a filename to this method, you must validate the input first. Passing a filename is deprecated in Symfony 2.2, and was removed in Symfony 3.0.

If an error occurs during parsing, the parser throws a ParseException exception indicating the error type and the line in the original YAML string where the error occurred:

1
2
3
4
5
6
7
use Symfony\Component\Yaml\Exception\ParseException;

try {
    $value = Yaml::parse(file_get_contents('/path/to/file.yml'));
} catch (ParseException $exception) {
    printf("Unable to parse the YAML string: %s", $exception->getMessage());
}

Objects for Mappings

2.7

Support for parsing mappings as objects was introduced in Symfony 2.7.

Yaml mappings are basically associative arrays. You can instruct the parser to return mappings as objects (i.e. \stdClass instances) by setting the fourth argument to true:

1
2
3
$object = Yaml::parse('{"foo": "bar"}', false, false, true);
echo get_class($object); // stdClass
echo $object->foo; // bar

Writing YAML Files

The dump() method dumps any PHP array to its YAML representation:

1
2
3
4
5
6
7
8
9
10
use Symfony\Component\Yaml\Yaml;

$array = array(
    'foo' => 'bar',
    'bar' => array('foo' => 'bar', 'bar' => 'baz'),
);

$yaml = Yaml::dump($array);

file_put_contents('/path/to/file.yml', $yaml);

If an error occurs during the dump, the parser throws a DumpException exception.

Array Expansion and Inlining

The YAML format supports two kind of representation for arrays, the expanded one, and the inline one. By default, the dumper uses the expanded representation:

1
2
3
4
foo: bar
bar:
    foo: bar
    bar: baz

The second argument of the dump() method customizes the level at which the output switches from the expanded representation to the inline one:

1
echo Yaml::dump($array, 1);
1
2
foo: bar
bar: { foo: bar, bar: baz }
1
echo Yaml::dump($array, 2);
1
2
3
4
foo: bar
bar:
    foo: bar
    bar: baz

Indentation

By default the YAML component will use 4 spaces for indentation. This can be changed using the third argument as follows:

1
2
// uses 8 spaces for indentation
echo Yaml::dump($array, 2, 8);
1
2
3
4
foo: bar
bar:
        foo: bar
        bar: baz

Invalid Types and Object Serialization

By default the YAML component will encode any "unsupported" type (i.e. resources and objects) as null.

Instead of encoding as null you can choose to throw an exception if an invalid type is encountered in either the dumper or parser as follows:

1
2
3
4
5
// throws an exception if a resource or object is encountered
Yaml::dump($data, 2, 4, true);

// throws an exception if an encoded object is found in the YAML string
Yaml::parse($yaml, true);

However, you can activate object support using the next argument:

1
2
3
4
5
6
7
8
9
$object = new \stdClass();
$object->foo = 'bar';

$dumped = Yaml::dump($object, 2, 4, false, true);
// !!php/object:O:8:"stdClass":1:{s:5:"foo";s:7:"bar";}

$parsed = Yaml::parse($dumped, false, true);
var_dump(is_object($parsed)); // true
echo $parsed->foo; // bar

The YAML component uses PHP's serialize() method to generate a string representation of the object.

Caution

Object serialization is specific to this implementation, other PHP YAML parsers will likely not recognize the php/object tag and non-PHP implementations certainly won't - use with discretion!

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version