Oct 02 2009

YAML parser kit — PHP5 bindings

Category: AsteriskBipin Balakrishnan @ 8:54 pm

YAML(tm) (rhymes with ‘camel’) is a straightforward machine parsable data serialization format designed for human readability and interaction with scripting languages such as PHP, Perl and Python. YAML is optimized for data serialization,formatted dumping, configuration files, log files, Internet messaging and filtering. This specification describes the YAML information model and serialization format. PHP library packege php5-sync here parses YAML strings and converts them to PHP arrays. It can also converts PHP arrays to YAML strings.

Installing PHP binding of yaml

sudo apt-get install php5-sysc

Now you are ready to use YAML.

It’s tempting to think of YAML as being similar to XML, but in reality it’s not. Unlike XML, YAML doesn’t use elements and attributes to mark up data; rather, indentation is used to denote nested relationships, and punctuation elements like dashes (-) and colons (:) are used to mark lists and hashes of data items. To illustrate, consider the following simple YAML document, which sets up a hash containing five key-value pairs:
example of yaml file.

name : John Doe
tel  : 123-4567
fax  : 987-6543
email:
- john@domain.com
- jdoe@domain.com

Using yaml in php

Save the above example as sample.yaml

<?php
// get YAML data
$yaml = file_get_contents('sample.yaml');

// convert to PHP data structure and print
$data = syck_load($yaml);
print_r($data);
?>

will print the yaml in array format in the program

The reverse process will be like this.

<?php
// define PHP array
$data = array (
    'droids' =
array('r2d2', 'c3po'),
'heroes' =>
array(
'one' => array('luke', 'leia'),
'two' => array('han', 'chewbacca'))
);

// convert to YAML and print
$yaml = syck_dump($data);
echo $yaml;
?>

Leave a Reply