Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

Sample .ini file:

1 = 0;
2 = 1372240157;    // timestamp.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
304 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...