将数组转换为.ini文件 [英] Convert array to an .ini file

查看:243
本文介绍了将数组转换为.ini文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个.ini文件解析为一个数组,然后更改该数组的值并将其导出到相同的.ini文件中. 我设法读取了文件,但找不到任何简单的方法将其写回. 有什么建议吗?

I need to parse an .ini file into an array, and later change the values of the array and export it to the same .ini file. I managed to read the file, but didn’t find any simple way to write it back. Any suggestions?

示例.ini文件:

1 = 0;
2 = 1372240157;    // timestamp.

推荐答案

为了回写.ini文件,您需要创建自己的函数,因为PHP除了读取之外没有提供其他功能(可以在这里找到: http://php.net/manual/pl /function.parse-ini-file.php ).

In order to write the .ini file back, you need to create your own function, for PHP offers no functions out of the box other than for reading (which can be found here: http://php.net/manual/pl/function.parse-ini-file.php).

一个可能将多维数组封装为.ini-语法兼容字符串的函数示例可能看起来像这样:

An example of function that might encapsulate a multidimensional array to .ini-syntax compatible string might look like this:

function arr2ini(array $a, array $parent = array())
{
    $out = '';
    foreach ($a as $k => $v)
    {
        if (is_array($v))
        {
            //subsection case
            //merge all the sections into one array...
            $sec = array_merge((array) $parent, (array) $k);
            //add section information to the output
            $out .= '[' . join('.', $sec) . ']' . PHP_EOL;
            //recursively traverse deeper
            $out .= arr2ini($v, $sec);
        }
        else
        {
            //plain key->value case
            $out .= "$k=$v" . PHP_EOL;
        }
    }
    return $out;
}

您可以像这样测试它:

$x = [
  'section1' => [
    'key1' => 'value1',
    'key2' => 'value2',
    'subsection' => [
      'subkey' => 'subvalue',
      'further' => ['a' => 5],
      'further2' => ['b' => -5]]]];
echo arr2ini($x);

(请注意,短数组语法仅从PHP 5.4+起可用.)

(Note that short array syntax is available only since PHP 5.4+.)

还请注意,它不会保留您的问题中出现的评论.当是通过软件(而不是人类)来更新文件时,没有简单的方式来记住它们.

Also note that it doesn't preserve the comments that were present in your question. There are no easy ways to remember them, when it is software (as opposed to a human) that updates the file back.

这篇关于将数组转换为.ini文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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