1. 程式人生 > >PHP parse_ini_file函式的應用與擴充套件

PHP parse_ini_file函式的應用與擴充套件

parse_ini_file($filename, $process_sections = false, $scanner_mode = INI_SCANNER_NORMAL)解析一個配置檔案。filename要解析的檔名;process_sections設定為true時,得到一個多維陣列,包括配置檔案中每一節的名稱和設定,預設為false;解析成功返回關聯陣列,失敗返回false。列舉一下官網的例子,也引用了官網的擴充套件例項parse_ini_file_multi()。

下面是配置檔案內容:

[first_section]
one = 1
two = 2
name = test

[second_section]
path = '/tmp/test'
url = 'http://test.com/login.php'

[third_section]
php_version[] = '5.0'
php_version[] = '5.1'
php_version[] = '5.5'

[dictionary]
foo[debug] = true
foo[path] = /some/path

[fourth_section]
fold1.fold2.fold3 = 'a'
fold1.fold2.fold4 = 'b'
fold1.fold2.fold5 = 'b'

下面是PHP檔案內容:

function parse_ini_file_multi($file, $process_sections = false, $scanner_mode = INI_SCANNER_NORMAL){
	$explode_str = '.';
	$escape_char = "'";
	$data = parse_ini_file($file, $process_sections, $scanner_mode);
	if (!$process_sections) {
        $data = array($data);
    }
	foreach ($data as $section_key => $section) {
		foreach($section as $key => $value){
			if(strpos($key, $explode_str)){
				if(substr($key, 0, 1) !== $escape_char){
					$sub_keys = explode($explode_str, $key);
					$subs =& $data[$section_key];
					echo "\r\n".'========='."\r\n";
					print_r($subs);
					print_r($data);
					foreach($sub_keys as $sub_key){
						if (!isset($subs[$sub_key])) {
							$subs[$sub_key] = [];
						}
						$subs =& $subs[$sub_key];
						echo "\r\n".'++++++++'."\r\n";
						print_r($subs);
						print_r($data);
					}
					$subs = $value;
					echo "\r\n".'----------'."\r\n";
					print_r($subs);
					print_r($data);
					unset($data[$section_key][$key]);
				}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;
}

$arr = parse_ini_file('file.ini');
print_r($arr);
echo "\r\n".'================='."\r\n";
$arr = parse_ini_file_multi('file.ini',true);
echo "\r\n".'================='."\r\n";
print_r($arr);