PHP数组到一个.ini文件 [英] PHP array to a .ini file

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

问题描述

我需要读取一个.ini文件到一个数组,后来又改变数组的值,并将其导出到同一个.ini文件。
我设法读取该文件,但并没有发现任何简单的方法来写回。
有什么建议?

样本.ini文件:

  1 = 0;
2 = 1372240157; //时间戳。


解决方案

为了写的.ini 文件恢复,你需要创建自己的功能,PHP没有提供的功能出比其他的箱子阅读(这可以在这里找到:的 http://php.net/manual/pl/function.parse-ini-file.php )。

这可能封装了多维数组的.ini -syntax兼容的字符串函数的例子可能是这样的:

函数arr2ini(数组$ A,数组$父=阵列())
{
    从$ ='';
    的foreach($ A $为K => $ V)
    {
        如果(is_array($ V))
        {
            //款情况
            //所有部分合并成一个阵列...
            $秒= array_merge((阵列)$母公司(阵列)$ K);
            //添加部分信息输出
            $出来。='['。加入('。',$秒)。 ']'。 PHP_EOL;
            //递归遍历更深
            $ OUT = arr2ini($ V,$秒)。
        }
        其他
        {
            //普通键盘>案值
            $出。=$ K = $ V。 PHP_EOL;
        }
    }
    返回$出;
}

您可以测试它是这样的:

$ X = [
  SECTION1'=> [
    '键1'=> VALUE1,
    '键2'=> '值',
    '款'=> [
      '子'=> 子值,
      '进一步'=> ['A'=> 5],
      further2'=> ['B'=> -5]]]];
回声arr2ini($ X);

(注意,短阵语法仅自PHP 5.4 +)。

还要注意的是它没有preserve的评论的是你的问题present。有没有简单的方法来记住他们,当它是更新文件后面软件(而不是人)。

I need to read a .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 found any simple way to write it back. any suggestions?

sample .ini file:

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

解决方案

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).

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;
}

You can test it like this:

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

(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.

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

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