PHP YAML parsing

To parse YAML, the easiest and preferred way would be using a pure PHP implementation. Sypc is such a YAML parser and it is used by WP-CLI. It has no dependencies, to use it you just need to download it and include a proper file in your own PHP file.

PHP official site provides a YAML extension that is not shipped with PHP. It is a bit complicated to use this extension, you need to install it and make changes to your php.ini (meaning you may make changes to your server) to load it. And this extension requires some other dependencies that you need to install them first.

Parse YAML with pure PHP implementation — Spyc

Download Sypc and unzip it to a proper location.

Examples

Parse YAML with Spyc.

require_once( './spyc/Spyc.php' );

//---------------Parse a YAML stream

$str = 
'---
title: PHP YAML parsing
author: John
---';
$meta = spyc_load( $str );
var_dump( $meta );

/* output:
array(2) {
  ["title"]=>
  string(16) "PHP YAML parsing"
  ["author"]=>
  string(4) "John"
}
*/

//----------------Parse a YAML file

$meta = spyc_load_file( 'meta.yaml' );

It is also able to dump an array to a YAML string.

require_once( './spyc/Spyc.php' );

//----------------Dump an array to a YAML string.

$arr = [
    'title' => 'PHP YAML parsing',
    'author' => 'John'
];
$yaml = spyc_dump( $arr );
echo $yaml;

/* output:
title: PHP YAML parsing
author: John
*/

Parse YAML with PHP extension — YAML

Before you are able to use YAML extension, first check the requirements and install it.

APIs

All the APIs provide a callback parameter.

// Parse a YAML stream
yaml_parse ( string $input [, int $pos = 0 [, int &$ndocs [, array $callbacks = NULL ]]] ) : mixed

// Parse a Yaml stream from a file
yaml_parse_file ( string $filename [, int $pos = 0 [, int &$ndocs [, array $callbacks = NULL ]]] ) : mixed

Others:

  • yaml_parse_url(), parse a Yaml stream from a URL.
  • yaml_emit(), returns the YAML representation of a value.
  • yaml_emit_file().

Examples

$yaml = <<<EOD
---
title: PHP YAML parsing
author: John
tags:
  - php
  - yaml
---
EOD;

$parsed = yaml_parse( $yaml );
var_dump( $parsed );

/* output:
array(3) {
  ["title"]=>
  string(16) "PHP YAML parsing"
  ["author"]=>
  string(4) "John"
  ["tags"]=>
  array(2) {
    [0]=>
    string(3) "php"
    [1]=>
    string(4) "yaml"
  }
}
*/

For a more complicated YAML steam with an variable references to other one and two-dimension array, see yaml-parse.