Basics of YAML Parsing in PHP

I know I’ve been on hiatus for a while and have neglected to update my website in over a year. That’s what happens when you get married and pop out a kid three months early. But now that I have more time on my hands I promise to devote a little more time to the website, starting with some of the basic PHP tutorials that my readers have grown to know and love.

First off, YAML is not a markup language, nor does it claim to be (YAML Aint a Markup Language), but it does represent a decent way to statically store arrays of data that are easily parsed by almost any programming language.  I recently had to write a script to parse out domain data from a cPanel “userdata” file, which is a YAML-formatted template that cPanel uses to build an httpd.conf file:

addon_domains: {}

cp_php_magic_include_path.conf: 0

Essentially with a YAML file you’ll treat the data like a multi-dimensional array – key/value pairs are separated by a colon, and sequences are prefaced by dashes.  PHP makes it easy to parse these files with the YAML PECL module.

First things first, does your PHP installation have YAML support?

root@server [~]# php -m |grep yaml

To install YAML for PHP:

Install libYAML


tar -xvzf yaml-1.1.0.tgz
cd yaml-1.1.0
./configure && make && make install

Then make sure that is located in your php.ini

In its simplest form, our YAML file can be parsed as so:

$parsed = yaml_parse_file($file);

This will return the YAML file as a multi-dimensional array:

    [addon_domains] => Array

    [cp_php_magic_include_path.conf] => 0
    [main_domain] =>
    [parked_domains] => Array
            [0] =>

    [sub_domains] => Array
            [0] =>
            [1] =>
            [2] =>


Then from here, we can simply parse the array as usual.  For example, this will print out all of the items under the parked_domains key:

foreach($parsed['parked_domains'] as $key=>$value){
    echo "$value\n";
Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>