在开发项目的过程中,经常用到读取参数配置,有好种方法,有配置成数组形式,有读取YML形式等,今天说说一下采用PHP内置函数parse_ini_file,读取配置形式像php.ini
的格式。参数说明:array parse_ini_file ( string $filename [, bool $process_sections ] ) parse_ini_file() 载入一个由 filename 指定的 ini 文件,并将其中的设置作为一个联合数组返回。如果将最后的 process_sections 参数设为 TRUE,将得到一个多维数组,包括了配置文件中每一节的名称和设置。process_sections 的默认值是 FALSE。如果 ini 文件中的值包含任何非字母数字的字符,需要将其括在双引号中(")。注释用;符号
废话少说了,直接看实例:
conifg.ini(可以设置为其它类型后缀名)如下:
PHP代码
- ; This is a sample configuration file
- ; Comments start with ';', as in php.ini
- [test]
- one = 1
- five = 5
- animal = BIRD
- [beta]
- path = "/usr/local/bin"
- URL = "http://www.9streets.cn"
下面是我在本地调试代码,如下:
PHP代码
- <?php
- $result = parse_ini_file('config.ini');
- print_r($result);
- $result1 = parse_ini_file('config.ini', true);
- print_r($result1);
- ?>
查看结果源代码如下:
XML/HTML代码
- Array
- (
- [one] => 1
- [five] => 5
- [animal] => BIRD
- [path] => /usr/local/bin
- [URL] => http://www.9streets.cn
- )
- Array
- (
- [test] => Array
- (
- [one] => 1
- [five] => 5
- [animal] => BIRD
- )
- [beta] => Array
- (
- [path] => /usr/local/bin
- [URL] => http://www.9streets.cn
- )
- )
这个配置看起来简单吧!如果还不懂的话,查看一下手册,特别提醒一下,本人目前只摸索到三维的方法,如果有朋友能搜到大于三维数组的,麻烦留一下脚印哈!三维配置地址如下:
PHP代码
- [test]
- test1[]=2;
- test1[]=3;
- test1[]=4;