Spyc PHP读写YAML

jackxiang 2010-1-26 09:48 | |
官方网站

http://spyc.sourceforge.net/
DownLoad:

spyc-0.4.5.zip
Spyc只有2个类方法


include('spyc.php');

// 读取YAML文件,生成数组
$yaml = Spyc::YAMLLoad('spyc.yaml');

// 将数组转换成YAML文件
$array['name']  = 'andy';
$array['site'] = '21andy.com';
$yaml = Spyc::YAMLDump($array);


php.ini读取ini的解析方式那种配置没法支持多维数组,So,我对yaml生成多维数组很感兴趣,主要想做一下配置文件,如下:
yml:
switches:
  - { row: 0, col: 0, func: {tx: [0, 1]} }

转为php多维数组如下:
spyc.yaml :

family:
  name:xiangs
  general:{frist: {sonone:jackxinag, second: jjjjj}, secondson: {one: 1, two: 2}}


test.php

<?php
include('spyc.php');

// 读取YAML文件,生成数组
$yaml = Spyc::YAMLLoad('spyc.yaml');
print_r($yaml);
?>




PHP code:
Array
(
    [family] => Array
        (
            [name] => xiangs
            [general] => Array
                (
                    [frist] => Array
                        (
                            [0] => sonone:jackxinag
                            [second] => jjjjj
                        )

                    [secondson] => Array
                        (
                            [one] => 1
                            [two] => 2
                        )

                )

        )

)


特别注意:冒号后需要有一个空格,{} 是php哈希,key=>value ,{key: value},空格。
{one: 1, two: 2},one=>1,two=>2,注意1, two,空格,1逗号后面要有空格!!!否则就变为:
          
      
                    [secondson] => Array
                        (
                            [one] => Array
                                (
                                    [1,two] => 2
                                )

                        )


而不是:

                    [secondson] => Array
                        (
                            [one] => 1
                            [two] => 2
                        )


这就是:secondson: {one: 1,two: 2} 和 secondson: {one: 1, two: 2} 的区别,空格是yaml的解析核心!!!

关于| 和 >
family:

   name: |
         'ddd
         dfdf
         dfd'  
family2:
   name: >
         'ddd
         dfdf
         dfd'
  
注意对齐:这儿的name是4个空格,这儿就ddd前面有4个,如果是familiy,那就是2个,否则解析会出问题。

结果:

Array
(
    [family] => Array
        (
            [name] => 'ddd
dfdf
dfd'
        )

    [family2] => Array
        (
            [name] => 'ddd dfdf dfd'
        )

)

换行和空格的转换, | 为换行,>空格!



<?php
include "Spyc.class.php";
function parseYaml($string){
    $data = Spyc::YAMLLoadString($string);
    return $data;
}
?>

作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:https://jackxiang.com/post/2635/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!


最后编辑: jackxiang 编辑于2010-10-26 16:07
评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]