解析.ini文件时,请保持重复键的所有值 [英] Maintain all values of duplicate keys when parsing .ini file

查看:120
本文介绍了解析.ini文件时,请保持重复键的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php.ini文件,其中包含以下几行:

I have a php.ini file which contains the following lines:

; ...settings

extension=pdo_mysql
extension=pdo_oci

; settings...

所以我这样做:

var_dump( parse_ini_file( '/path/to/php.ini' )[ 'extension' ] );

但是我所得到的只是string(7) "pdo_oci",所以解析似乎只是保留了extension设置为的最终值.

But all I get is string(7) "pdo_oci" so it looks like the parse simply maintains the final value which extension was set to.

有没有办法使extension键返回一个数组?

Is there a way to make the extension key return an array instead?

我了解PHP的内部人员可能使用专用的解析器来显式处理这种情况,以使扩展正确加载,但这并不能帮助我实现目标.

I understand that PHP's internals probably use a dedicated parser to explicitly handle this situation so that extensions load properly but that does not help me achieve my goal.

推荐答案

由于ini文件的键成为数组的键,因此将覆盖这些值.我想出了自己的功能.

Since the keys of the ini file become the keys to the array, the values are overridden. I came up with my own function.

代码:

function my_parse_ini($file){
    $arr = array();
    $handle = fopen($file, "r");
    if ($handle) {
        while (($line = fgets($handle)) !== false) {
            $parsed = parse_ini_string($line);
            if(empty($parsed)){ continue; }
            $key = key($parsed);
            if(isset($arr[$key])){
                if(!is_array($arr[$key])){
                    $tmp = $arr[$key];
                    $arr[$key] = array($tmp);
                }
                $arr[$key][] = $parsed[$key];
            }else{
                $arr[$key] = $parsed[$key];
            }
        }
        fclose($handle);
        return $arr;
    } else {
        // error opening the file.
    } 
}

调用它传递要解析的文件,如下所示:

Call it passing the file to be parsed, like so:

$parsed = my_parse_ini('/path/to/php.ini');


结果:($parsed)

对于包含

; ...settings

extension=pdo_mysql
extension=pdo_oci

foo=test
bar=ok
foo=teste1
; settings...

这是输出:

Array
(
    [extension] => Array
        (
            [0] => pdo_mysql
            [1] => pdo_oci
        )

    [foo] => Array
        (
            [0] => test
            [1] => teste1
        )

    [bar] => ok
)

这篇关于解析.ini文件时,请保持重复键的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆