PHP YAML 解析器

有人知道一个很好的 YAML PHP 解析器吗?如果是这样,这个图书馆的优点和缺点是什么?

60038 次浏览

The symfony framework makes very heavy use of YAML, this blog post by Grégoire Hubert demonstrates using their YAML library in a non-symfony project.

Spyc: https://github.com/mustangostang/spyc

Pure PHP implementation, so you don't need to make any modifications to the server for installation. If speed is of dire concern, it might not be the ideal solution, but if you're using YAML for configurations or relatively low-volume use, it is a fantastic solution.

Given a YAML document, Spyc will return an array that you can use however you see fit.

require_once "spyc.php";
$data = Spyc::YAMLLoad($myfile);

Given an array, Spyc will return a string which contains a YAML document built from your data.

$yaml_str = Spyc::YAMLDump($myarray);

If you're using a lot of YAML in your project you may find that the pure PHP libraries like spyc or Symfony YAML are not fast enough. There are at least two PHP bindings for C YAML parsers:

  • yaml - a wrapper for the LibYAML YAML 1.1 parser library
  • syck - a wrapper for the Syck YAML 1.0 parser library

Try sfYaml, it is the best I know.

Symfony and Doctrine ORM are using this one.

To get it, you may Download Doctrine 1.2 and extract sfYaml from vendor directory.

Let us know if it suits your needs.

If you need to test your YAML quickly, I built: http://yaml-online-parser.appspot.com/ . It helps me write YAML, especially while just learning.

Last updated: July 26th, 2017

Here's a summary of the state of YAML in PHP:

  • Wrappers to C libraries: You'll probably want these if you need sheer speed:
    • php-yaml: Wrapper for LibYAML. Available as a PECL extension; it is also the one on PHP's docs.
    • syck: Binding to syck; also available as a PECL extension. (dated, see below)

  • Pure PHP implementations:

    • sfYaml: Symfony's YAML component. You can see its authors' motivations here. He wanted something that was "easy to use, fast, unit tested and had clear error messages."
    • spyc: YAML parser without dependencies

At the time of this writing, the latest versions release dates for the aforementioned libraries and the versions of the YAML spec (1.2 is the latest version) they support are:

php-yaml   1.3.0     2016-09-24     YAML 1.1  [PHP 5]
php-yaml   2.0.0     2016-09-24     YAML 1.1  [PHP 7]
syck       0.9.3     2008-11-18     YAML 1.0
sfYaml     3.3.5     2017-06-15     YAML 1.1, most of 1.2
spyc       0.6.2     2017-02-24     YAML 1.1

Symfony2 has a YAML component which supports most of the YAML 1.2 spec

https://github.com/symfony/Yaml