验证中...
本周日【珠海源创会】一起聊聊:PingCAP分布式事务、支付宝移动端实践、GSBN技术框架选型,点此报名占座
parse_ini_file()及扩展函数解析ini文件
原始数据 复制代码
在PHP网站开发的过程中,往往会用到读取ini参数配置文件,比如需要访问一些复杂的借口,就可以直接在参数配置文件里面修改参数,然后再php脚本里面直接读取执行。而php有一个可以直接读取ini配置文件的函数parse_ini_file(),并以数组的形式返回。下面详细讲解一下采用PHP内置函数parse_ini_file,读取ini配置文件。
参数说明:array parse_ini_file ( string $filename [, bool $process_sections ] ) parse_ini_file() 载入一个由 filename 指定的 ini 文件,返回一个联合数组。如果将 process_sections 参数设为 TRUE,将得到一个多维数组,包括了配置文件中每一节的名称和设置。process_sections 的默认值是 FALSE,
返回将每一节合并后的数组。ini文件
; 注释
[] 模块
key = value
config.ini(可以设置为其它类型后缀名)如下:
; This is a sample configuration file
; Comments start with ';', as in php.ini
[first_section]
one = 1
five = 5
animal = BIRD
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"
[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"
PHP脚本测试代码,如下:
<?php
$re = parse_ini_file('./config.ini', true);
print_r($re);
$re = parse_ini_file('./config.ini');
print_r($re);
parse_ini_file()函数,无法解析ini文件中的多维数组形式,这就需要自己手动加入下面的parse_ini_file_multi()方法,来解析大于三维数组的ini文件。特别说明的是,在PHP官网的手册中的parse_ini_file_multi()存在一个错误,下面代码中已经修复。
下面看一下parse_ini_file_multi()函数的实例详解!
parse_ini_file_multi()函数具体实现:
<?php
function parse_ini_file_multi($file, $process_sections = false, $scanner_mode = INI_SCANNER_NORMAL) {
$explode_str = '.';
$escape_char = "'";
// load ini file the normal way
$data = parse_ini_file($file, $process_sections, $scanner_mode);
if (!$process_sections) {
$data = array($data);
}
foreach ($data as $section_key => $section) {
// loop inside the section
foreach ($section as $key => $value) {
if (strpos($key, $explode_str)) {
if (substr($key, 0, 1) !== $escape_char) {
// key has a dot. Explode on it, then parse each subkeys
// and set value at the right place thanks to references
$sub_keys = explode($explode_str, $key);
$subs =& $data[$section_key];
foreach ($sub_keys as $sub_key) {
if (!isset($subs[$sub_key])) {
$subs[$sub_key] = '';
}
$subs =& $subs[$sub_key];
}
// set the value at the right place
$subs = $value;
// unset the dotted key, we don't need it anymore
unset($data[$section_key][$key]);
}
// we have escaped the key, so we keep dots as they are
else {
$new_key = trim($key, $escape_char);
$data[$section_key][$new_key] = $value;
unset($data[$section_key][$key]);
}
}
}
}
if (!$process_sections) {
$data = $data[0];
}
return $data;
}
[normal]
foo = bar
; use quotes to keep your key as it is
'foo.with.dots' = true
[array]
foo[] = 1
foo[] = 2
[dictionary]
foo[debug] = false
foo[path] = /some/path
[multi]
foo.data.config.debug = true
foo.data.password = 123456
<?php
$result = parse_ini_file_multi('file.ini', true);
print_r($result);

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助

12_float_left_people 12_float_left_close