用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');