YAML

6

YAML is another useful human-readable format for structured data representation. It has even less of punctuation symbols than JSON so the format is absolutely easy to read:

library:
    authors:
        - name: Sam
          age:  19

        - name: Jennifer
          age:  23

    books:
        - name:   Seven best spices
          author: Sam

        - name:   A book of night tales
          author: Jennifer

There are four YAML functions you should learn today. Reading YAML document from a file:

$library = yaml_parse_file(__DIR__ . '/library.yaml');
var_dump($library);

Parsing YAML document from a string:

$yaml = file_get_contents(__DIR__ . '/library.yaml');
$library = yaml_parse($yaml);
var_dump($library);

Encoding a YAML document can be done in a similar way. Creating a YAML file from a given PHP object or array:

$library =
[
    # Key-value pairs
];

yaml_emit_file(__DIR__ . '/library.yaml', $library);

Encoding a YAML document into a string:

$library =
[
    # Key-value pairs
];

$yaml = yaml_emit($library);
echo $yaml;

Things you should know about PHP YAML functions:

Parsing functions always return an associative array. You can't ask them to return an instance of stdClass like you can with json_decode.

You can't specify an indention size when emitting a YAML document. It is always set to 2.

Lesson 16
Share this page:

Learning plan

14. Operators
We should learn all PHP operators in details before we could continue
15. stdClass
The very basics of stdClass PHP class
16. JSON
How to work with JSON in PHP
17. YAML
How to work with YAML in PHP
Some additional functions you should learn to work with PHP strings