Use include in YAML with PHP


You may want to split your large YAML file into smaller files and configure them to include each other. YAML doesn't support includes out-of-the-box.

However YAML does support user-defined tags, so if you're using YAML with PHP you can easily implement YAML includes by yourself:

function yaml_parse_file_inc($filename)
    return yaml_parse_file($filename, 0, $ndocs,
        '!include' => function($value, $tag, $flags) use($filename)
            $directory = dirname($filename);
            return yaml_parse_file_inc("$directory/$value");

$config = yaml_parse_file_inc('config.yaml');

Note that you should use the same function recursively inside the callback to make nested includes work. Now you can split your YAML files and keep your things neat:

    - css/style.css     # Just a string value
    - css/normalize.css # Just a string value

    desktop: !include templates/desktop.yaml # Include YAML from YAML
    mobile:  !include templates/mobile.yaml  # So you can YAML while you YAML ;)
Rate this post:
Share this page:

See also how to:

How to make POST and other types of HTTP requests and add custom HTTP headers with file_get_contents function in PHP
How to run your PHP or Bash script as root in the most secure way
How to use modern MaxMind GeoIP API in PHP
How to protect your website forms from unwanted spam bots
How to create a well-crafted RSS feed for a website and configure it property