Basics of YAML Parsing in PHP

Posted by Nessa | Posted in , | Posted on June 22, 2012

0

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
main_domain: v-nessa.net
parked_domains:
  - v-nessa.com
sub_domains:
  - mail.v-nessa.net
  - cpanel.v-nessa.net
  - anothersubdomain.v-nessa.net

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

Then:


wget http://pecl.php.net/get/yaml-1.1.0.tgz
tar -xvzf yaml-1.1.0.tgz
cd yaml-1.1.0
phpize
./configure && make && make install

Then make sure that yaml.so is located in your php.ini

extension=yaml.so

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

$file="/var/cpanel/userdata/myuser/main";
$parsed = yaml_parse_file($file);
 
print_r($parsed);

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

Array
(
    [addon_domains] => Array
        (
        )

    [cp_php_magic_include_path.conf] => 0
    [main_domain] => v-nessa.net
    [parked_domains] => Array
        (
            [0] => v-nessa.com
        )

    [sub_domains] => Array
        (
            [0] => mail.v-nessa.net
            [1] => cpanel.v-nessa.net
            [2] => anothersubdomain.v-nessa.net
        )

)

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!

Post a comment