解析“高级”使用 PHP 的 INI 文件

发布于 2024-09-09 04:34:28 字数 1161 浏览 7 评论 0原文

基本上,我想要一种简单、容易、单文件的方法来解析具有“高级”功能的 INI 文件,例如节继承和属性嵌套,例如 Zend_Config_Ini

例如:

[foo]
a = 1
b.a = 2
b.b = 3
b.c = 4
c = 5

[bar : foo]
b.b = 17
c = 42

将解析为

array(
  'foo'=>array(
    'a'=>'1',
    'b'=>array(
      'a'=>'2',
      'b'=>'3',
      'c'=>'4'
    ),
    'c'=>'5'
  ),
  'bar'=>array(
    'a'=>'1',
    'b'=>array(
      'a'=>'2',
      'b'=>'17',
      'c'=>'4'
    ),
    'c'=>'42'
  )
)

PHP 的内置 parse_ini_file,除了具有简单部分和简单键的简单 INI 之外,不处理任何其他内容。

我使用 Zend_Config_Ini 的问题是,我必须包含几乎整个 Zend_Config 子包,并且非常臃肿且可配置。

是否有一个小型简单的库可用于解析此内容?
如果没有,是否有一个我没有看到的简单实现?

我所说的“小而简单”是指类似 INI 文件的 sfYaml 之类的东西。

在我(非常缺乏经验)的眼中,我必须使用 parse_ini_file 解析一次,然后返回并解析继承,然后运行每个部分并递归地扩展键...

更新< /strong>:由于这似乎是一个流行的问题,我想指出 我有一个简单的类在GitHub,随时发送拉取请求、问题等。

Basically, I would like a simple, easy, one-file way to parse an INI file with "advanced" features, like section inheritance and property nesting, like Zend_Config_Ini.

For example:

[foo]
a = 1
b.a = 2
b.b = 3
b.c = 4
c = 5

[bar : foo]
b.b = 17
c = 42

Would parse into

array(
  'foo'=>array(
    'a'=>'1',
    'b'=>array(
      'a'=>'2',
      'b'=>'3',
      'c'=>'4'
    ),
    'c'=>'5'
  ),
  'bar'=>array(
    'a'=>'1',
    'b'=>array(
      'a'=>'2',
      'b'=>'17',
      'c'=>'4'
    ),
    'c'=>'42'
  )
)

PHP's built-in parse_ini_file, doesn't handle anything other than simple INI's with simple sections and simple keys.

My problem with using Zend_Config_Ini is that I would have to include virtually the whole Zend_Config subpackage, and is super-bloated and configurable.

Is there a small and simple library available to parse this?
If not, is there an easy implementation I'm not seeing?

By small and simple, I mean something like the sfYaml of INI files.

To my (very inexperienced) eyes, I would have to parse through once with parse_ini_file, then come back and resolve inheritance, then run through each section and expand the keys recursively...

UPDATE: Since this seems to be a popular question, I would like to note that I have a simple class implementing this on GitHub, feel free to send pull requests, issues, etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不乱于心 2024-09-16 04:34:28

不确定我是否应该编辑旧答案或添加新答案。

尝试一下这个版本,应该就是您要找的。

function parse_ini_advanced($array) {
    $returnArray = array();
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $e = explode(':', $key);
            if (!empty($e[1])) {
                $x = array();
                foreach ($e as $tk => $tv) {
                    $x[$tk] = trim($tv);
                }
                $x = array_reverse($x, true);
                foreach ($x as $k => $v) {
                    $c = $x[0];
                    if (empty($returnArray[$c])) {
                        $returnArray[$c] = array();
                    }
                    if (isset($returnArray[$x[1]])) {
                        $returnArray[$c] = array_merge($returnArray[$c], $returnArray[$x[1]]);
                    }
                    if ($k === 0) {
                        $returnArray[$c] = array_merge($returnArray[$c], $array[$key]);
                    }
                }
            } else {
                $returnArray[$key] = $array[$key];
            }
        }
    }
    return $returnArray;
}
function recursive_parse($array)
{
    $returnArray = array();
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $array[$key] = recursive_parse($value);
            }
            $x = explode('.', $key);
            if (!empty($x[1])) {
                $x = array_reverse($x, true);
                if (isset($returnArray[$key])) {
                    unset($returnArray[$key]);
                }
                if (!isset($returnArray[$x[0]])) {
                    $returnArray[$x[0]] = array();
                }
                $first = true;
                foreach ($x as $k => $v) {
                    if ($first === true) {
                        $b = $array[$key];
                        $first = false;
                    }
                    $b = array($v => $b);
                }
                $returnArray[$x[0]] = array_merge_recursive($returnArray[$x[0]], $b[$x[0]]);
            } else {
                $returnArray[$key] = $array[$key];
            }
        }
    }
    return $returnArray;
}

可以这样调用:

$array = parse_ini_file('test.ini', true);
$array = recursive_parse(parse_ini_advanced($array));

这可以做得更好/更清晰,但对于一个简单的解决方案来说,它应该工作得很好。

如果您的配置是:

[foo]
a = 1
b.a = 2
b.b = 3
b.c = 4
c = 5

[bar : foo]
b.x.c = 33
b.b = 17
c = 42

[hot : bar : foo]
b.a = 83
b.d = 23

输出应该是:

Array
(
[foo] => Array
    (
        [a] => 1
        [b] => Array
            (
                [a] => 2
                [b] => 3
                [c] => 4
            )

        [c] => 5
    )

[bar] => Array
    (
        [a] => 1
        [b] => Array
            (
                [a] => 2
                [b] => 17
                [c] => 4
                [x] => Array
                    (
                        [c] => 33
                    )

            )

        [c] => 42
    )

[hot] => Array
    (
        [a] => 1
        [b] => Array
            (
                [a] => 83
                [b] => 17
                [c] => 4
                [x] => Array
                    (
                        [c] => 33
                    )

                [d] => 23
            )

        [c] => 42
    )
)

Not sure if I should edit my old answer or add a new one.

Try this version of it, should be what you're looking for.

function parse_ini_advanced($array) {
    $returnArray = array();
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $e = explode(':', $key);
            if (!empty($e[1])) {
                $x = array();
                foreach ($e as $tk => $tv) {
                    $x[$tk] = trim($tv);
                }
                $x = array_reverse($x, true);
                foreach ($x as $k => $v) {
                    $c = $x[0];
                    if (empty($returnArray[$c])) {
                        $returnArray[$c] = array();
                    }
                    if (isset($returnArray[$x[1]])) {
                        $returnArray[$c] = array_merge($returnArray[$c], $returnArray[$x[1]]);
                    }
                    if ($k === 0) {
                        $returnArray[$c] = array_merge($returnArray[$c], $array[$key]);
                    }
                }
            } else {
                $returnArray[$key] = $array[$key];
            }
        }
    }
    return $returnArray;
}
function recursive_parse($array)
{
    $returnArray = array();
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $array[$key] = recursive_parse($value);
            }
            $x = explode('.', $key);
            if (!empty($x[1])) {
                $x = array_reverse($x, true);
                if (isset($returnArray[$key])) {
                    unset($returnArray[$key]);
                }
                if (!isset($returnArray[$x[0]])) {
                    $returnArray[$x[0]] = array();
                }
                $first = true;
                foreach ($x as $k => $v) {
                    if ($first === true) {
                        $b = $array[$key];
                        $first = false;
                    }
                    $b = array($v => $b);
                }
                $returnArray[$x[0]] = array_merge_recursive($returnArray[$x[0]], $b[$x[0]]);
            } else {
                $returnArray[$key] = $array[$key];
            }
        }
    }
    return $returnArray;
}

Would be called like this:

$array = parse_ini_file('test.ini', true);
$array = recursive_parse(parse_ini_advanced($array));

This could be done a lot better/clearer but for a simple solution it should work just fine.

If your config is:

[foo]
a = 1
b.a = 2
b.b = 3
b.c = 4
c = 5

[bar : foo]
b.x.c = 33
b.b = 17
c = 42

[hot : bar : foo]
b.a = 83
b.d = 23

The output should be:

Array
(
[foo] => Array
    (
        [a] => 1
        [b] => Array
            (
                [a] => 2
                [b] => 3
                [c] => 4
            )

        [c] => 5
    )

[bar] => Array
    (
        [a] => 1
        [b] => Array
            (
                [a] => 2
                [b] => 17
                [c] => 4
                [x] => Array
                    (
                        [c] => 33
                    )

            )

        [c] => 42
    )

[hot] => Array
    (
        [a] => 1
        [b] => Array
            (
                [a] => 83
                [b] => 17
                [c] => 4
                [x] => Array
                    (
                        [c] => 33
                    )

                [d] => 23
            )

        [c] => 42
    )
)
妄想挽回 2024-09-16 04:34:28

首先回答一件事,属性嵌套可以从 parse_ini_file() 获得,将第二个参数设置为 true ,即 parse_ini_file('test.ini', true);这将为您提供一个多维数组,即

Array
(
    [foo] => Array
        (
            [a] => 1
            [b.a] => 2
            [b.b] => 3
            [b.c] => 4
            [c] => 5
        )

    [bar : foo] => Array
        (
            [b.b] => 17
            [c] => 42
        )
)

这是一个小函数,它将解析 parse_ini_file() 返回的数组并将其转换为类别。

/**
 * Parse INI files Advanced
 * process_sections = true
 * scanner_mode = default
 * 
 * Supports section inheritance
 * and has property nesting turned on
 * 
 * @param string $filename
 * return array
 */
function parse_ini_file_advanced($filename) {
    $array = parse_ini_file($filename, true);
    $returnArray = array();
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $x = explode(':', $key);
            if (!empty($x[1])) {
                $x = array_reverse($x, true);
                foreach ($x as $k => $v) {
                    $i = trim($x[0]);
                    $v = trim($v);
                    if (empty($returnArray[$i])) {
                        $returnArray[$i] = array();
                    }
                    if (isset($array[$v])) {
                        $returnArray[$i] = array_merge($returnArray[$i], $array[$v]);
                    }
                    if ($k === 0) {
                        $returnArray[$i] = array_merge($returnArray[$i], $array[$key]);
                    }
                }
            } else {
                $returnArray[$key] = $array[$key];
            }
        }
    } else {
        return false;
    }

    return $returnArray;
}

它将返回:

Array
(
    [foo] => Array
        (
            [a] => 1
            [b.a] => 2
            [b.b] => 3
            [b.c] => 4
            [c] => 5
        )

    [bar] => Array
        (
            [a] => 1
            [b.a] => 2
            [b.b] => 17
            [b.c] => 4
            [c] => 42
        )
)

最后一次写入获胜,即
[bar2:foo2:bar:foo]
bar2 以其自己的数组中的设置获胜
注意:其他 3 个数组到那时都会存在。

希望这就是您正在寻找的。

First to answer one thing, property nesting is avilable from parse_ini_file(), set the second param to true i.e parse_ini_file('test.ini', true); That will give you a multidimensional array i.e

Array
(
    [foo] => Array
        (
            [a] => 1
            [b.a] => 2
            [b.b] => 3
            [b.c] => 4
            [c] => 5
        )

    [bar : foo] => Array
        (
            [b.b] => 17
            [c] => 42
        )
)

Here is a small function that will parse the array returned by parse_ini_file() and turn it into categories.

/**
 * Parse INI files Advanced
 * process_sections = true
 * scanner_mode = default
 * 
 * Supports section inheritance
 * and has property nesting turned on
 * 
 * @param string $filename
 * return array
 */
function parse_ini_file_advanced($filename) {
    $array = parse_ini_file($filename, true);
    $returnArray = array();
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $x = explode(':', $key);
            if (!empty($x[1])) {
                $x = array_reverse($x, true);
                foreach ($x as $k => $v) {
                    $i = trim($x[0]);
                    $v = trim($v);
                    if (empty($returnArray[$i])) {
                        $returnArray[$i] = array();
                    }
                    if (isset($array[$v])) {
                        $returnArray[$i] = array_merge($returnArray[$i], $array[$v]);
                    }
                    if ($k === 0) {
                        $returnArray[$i] = array_merge($returnArray[$i], $array[$key]);
                    }
                }
            } else {
                $returnArray[$key] = $array[$key];
            }
        }
    } else {
        return false;
    }

    return $returnArray;
}

It will return this:

Array
(
    [foo] => Array
        (
            [a] => 1
            [b.a] => 2
            [b.b] => 3
            [b.c] => 4
            [c] => 5
        )

    [bar] => Array
        (
            [a] => 1
            [b.a] => 2
            [b.b] => 17
            [b.c] => 4
            [c] => 42
        )
)

Last write wins i.e
[bar2 : foo2 : bar : foo]
bar2 wins with it's settings in it's own array
NOTE: the other 3 arrays WILL be there up to that point.

Hope this was what you were looking for.

盗梦空间 2024-09-16 04:34:28

我写了这样的东西,现在它对我来说工作正常:

        $config = array();
        $configSrc = parse_ini_file( $filePath, true );
        foreach( $configSrc as $sectionName => $section )
        {
            $config[$sectionName] = array();
            foreach( $section as $itemName => $item )
            {
                $itemNameArray = explode( '.', $itemName );
                eval( sprintf('$config[$sectionName][\'%s\'] = $item;', join("']['", $itemNameArray)) );
            }
        }

        // marge inheritance;
        foreach( $config as $sectionName => $section )
        {
            $ancestryArray = explode( ':', $sectionName );
            $ancestryCount = count( $ancestryArray );
            if( $ancestryCount > 1 )
            { //
                $config[$sectionNameTrimmed = trim($ancestryArray[0])] = array();
                $ancestryArray = array_reverse( array_slice($ancestryArray, 1) );
                foreach( $ancestryArray as $ancestryName )
                {
                    $ancestryName = trim( $ancestryName );
                    if( isset($config[$ancestryName]) ) {
                        $config[$sectionNameTrimmed] = array_replace_recursive( $config[$sectionNameTrimmed], $config[$ancestryName] );
                    }
                }

                $config[$sectionNameTrimmed] = array_replace_recursive( $config[$sectionNameTrimmed], $section );
                unset( $config[$sectionName] );
            }

        }

I've wrote something like this and for now it's working ok for me:

        $config = array();
        $configSrc = parse_ini_file( $filePath, true );
        foreach( $configSrc as $sectionName => $section )
        {
            $config[$sectionName] = array();
            foreach( $section as $itemName => $item )
            {
                $itemNameArray = explode( '.', $itemName );
                eval( sprintf('$config[$sectionName][\'%s\'] = $item;', join("']['", $itemNameArray)) );
            }
        }

        // marge inheritance;
        foreach( $config as $sectionName => $section )
        {
            $ancestryArray = explode( ':', $sectionName );
            $ancestryCount = count( $ancestryArray );
            if( $ancestryCount > 1 )
            { //
                $config[$sectionNameTrimmed = trim($ancestryArray[0])] = array();
                $ancestryArray = array_reverse( array_slice($ancestryArray, 1) );
                foreach( $ancestryArray as $ancestryName )
                {
                    $ancestryName = trim( $ancestryName );
                    if( isset($config[$ancestryName]) ) {
                        $config[$sectionNameTrimmed] = array_replace_recursive( $config[$sectionNameTrimmed], $config[$ancestryName] );
                    }
                }

                $config[$sectionNameTrimmed] = array_replace_recursive( $config[$sectionNameTrimmed], $section );
                unset( $config[$sectionName] );
            }

        }
木落 2024-09-16 04:34:28

另一种选择 - 这是配对、构建和解析。

function build_ini_string_nested( $data, $path = null ){
  $content = array();
  foreach( $data AS $key => $val ){
    if( is_array($val) ){
      $content[] = build_ini_string_nested( $val, ($path ? $path. '.' : '') . $key );
    }
    else if( $path ) {
      $content[] = $path . '[' . ($path && is_numeric($key) ? '' : $key) . '] = ' . $val;
    }
    else {
      $content[] = $key . ' = ' . $val;
    }
  }
  return implode("\n", $content);
}

function parse_ini_string_nested( $data, $path = null ){
  if( is_string($data) )
    $data = parse_ini_string($data);
  if( $path )
    foreach( $data AS $key => $val ){
      if( strpos( $key, $path.'.' ) !== false ){
        $find_node = explode('.', $path);
        $this_path = reset(explode('.', substr($key, strlen($path.'.'))));
        $node =& $data;
        do {
          $node =& $node[ array_shift($find_node) ];
        } while( count($find_node) );
        if( is_array($node[ $this_path ]) ){
          $node[ $this_path ][] = $val;
        }
        else {
          $node[ $this_path ] = $val;
        }
      }
    }
  else {
    $drop_keys = array();
    foreach( $data AS $key => $val ){
      if( count(explode('.', $key)) > 1 ){
        $path = reset(explode('.', $key));
        $data[ $path ] = array();
        $data = parse_ini_string_nested( $data, $path );
        $drop_keys[] = $key;
      }
    }
    foreach( $drop_keys AS $key ){
      unset($data[ $key ]);
    }
  }
  return $data;
}

Another option - this is the pair, build and parse.

function build_ini_string_nested( $data, $path = null ){
  $content = array();
  foreach( $data AS $key => $val ){
    if( is_array($val) ){
      $content[] = build_ini_string_nested( $val, ($path ? $path. '.' : '') . $key );
    }
    else if( $path ) {
      $content[] = $path . '[' . ($path && is_numeric($key) ? '' : $key) . '] = ' . $val;
    }
    else {
      $content[] = $key . ' = ' . $val;
    }
  }
  return implode("\n", $content);
}

function parse_ini_string_nested( $data, $path = null ){
  if( is_string($data) )
    $data = parse_ini_string($data);
  if( $path )
    foreach( $data AS $key => $val ){
      if( strpos( $key, $path.'.' ) !== false ){
        $find_node = explode('.', $path);
        $this_path = reset(explode('.', substr($key, strlen($path.'.'))));
        $node =& $data;
        do {
          $node =& $node[ array_shift($find_node) ];
        } while( count($find_node) );
        if( is_array($node[ $this_path ]) ){
          $node[ $this_path ][] = $val;
        }
        else {
          $node[ $this_path ] = $val;
        }
      }
    }
  else {
    $drop_keys = array();
    foreach( $data AS $key => $val ){
      if( count(explode('.', $key)) > 1 ){
        $path = reset(explode('.', $key));
        $data[ $path ] = array();
        $data = parse_ini_string_nested( $data, $path );
        $drop_keys[] = $key;
      }
    }
    foreach( $drop_keys AS $key ){
      unset($data[ $key ]);
    }
  }
  return $data;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文