用PHP处理YAML,经常使用的方法有两种:php
PECL扩展须要PHP 5.2以上,SPYC 须要PHP 5.3以上。git
我我的倾向于SPYC,由于PECL还须要编译安装,有的时候不方便(好比虚拟主机空间什么的),SPYC 虽然不支持 PHP 5.2,但5.2官方也不支持了,因此也不算什么不足。github
标准的PECL安装步骤,这里就不罗嗦了。json
假设咱们有这样一个数组:数组
$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
能够将其转化成YAMLapp
$yaml = yaml_emit($invoice);
使用yaml_parse
解析YAML:composer
$parsed = yaml_parse($yaml);
能够使用Composer安装,固然也能够直接require_once
或include
.函数
生成YAML:oop
<?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:post
<?php $Data = Spyc::YAMLLoad('spyc.yaml');
解析更经常使用,因此还提供了函数,上面的语句等价于:
<?php $Data = spyc_load_file('spyc.yaml');