用PHP处理YAML,常用的方法有两种:

  1. PECL扩展YAML
  2. spyc

PECL扩展需要PHP 5.2以上,SPYC 需要PHP 5.3以上。

我个人倾向于SPYC,因为PECL还需要编译安装,有的时候不方便(比如虚拟主机空间什么的),SPYC 虽然不支持 PHP 5.2,但5.2官方也不支持了,所以也不算什么不足。

1 PECL扩展YAML

安装

标准的PECL安装步骤,这里就不罗嗦了。

代码例子

假设我们有这样一个数组:

$addr = array(
    "given" => "Chris",
    "family"=> "Dumars",
    "address"=> array(
        "lines"=> "458 Walkman Dr.
        Suite #292",
        "city"=> "Royal Oak",
        "state"=> "MI",
        "postal"=> 48046,
      ),
  );
$invoice = array (
    "invoice"=> 34843,
    "date"=> "2001-01-23",
    "bill-to"=> $addr,
    "ship-to"=> $addr,
    "product"=> array(
        array(
            "sku"=> "BL394D",
            "quantity"=> 4,
            "description"=> "Basketball",
            "price"=> 450,
          ),
        array(
            "sku"=> "BL4438H",
            "quantity"=> 1,
            "description"=> "Super Hoop",
            "price"=> 2392,
          ),
      ),
    "tax"=> 251.42,
    "total"=> 4443.52,
    "comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.",
    );

使用yaml_emit可以将其转化成YAML

$yaml = yaml_emit($invoice);

使用yaml_parse解析YAML:

$parsed = yaml_parse($yaml);

2 使用spyc

安装

可以使用Composer安装,当然也可以直接require_onceinclude.

代码示例

生成YAML:

<?php
$array[] = 'Sequence item';
$array['The Key'] = 'Mapped value';
$array[] = array('A sequence','of a sequence');
$array[] = array('first' => 'A sequence','second' => 'of mapped values');
$array['Mapped'] = array('A sequence','which is mapped');
$array['A Note'] = 'What if your text is too long?';
$array['Another Note'] = 'If that is the case, the dumper will probably fold your text by using a block.  Kinda like this.';
$array['The trick?'] = 'The trick is that we overrode the default indent, 2, to 4 and the default wordwrap, 40, to 60.';
$array['Old Dog'] = "And if you want\n to preserve line breaks, \ngo ahead!";
$array['key:withcolon'] = "Should support this to";

$yaml = Spyc::YAMLDump($array,4,60);

解析YAML:

<?php
$Data = Spyc::YAMLLoad('spyc.yaml');

解析更常用,所以还提供了函数,上面的语句等价于:

<?php
$Data = spyc_load_file('spyc.yaml');

Lvye
2k 声望140 粉丝