By netrox


2009-08-12 19:58:31 8 Comments

I cannot find a way that easily lets me create a new file, treat it as an ini file (not php.ini or simiilar... a separate ini file for per user), and create/delete values using PHP. PHP seems to offer no easy way to create an ini file and read/write/delete values. So far, it's all just "read" - nothing about creating entries or manipulating keys/values.

6 comments

@Harri Siirak 2009-08-12 20:45:46

Found following code snippet from the comments of the PHP documentation:

function write_ini_file($assoc_arr, $path, $has_sections=FALSE) { 
    $content = ""; 
    if ($has_sections) { 
        foreach ($assoc_arr as $key=>$elem) { 
            $content .= "[".$key."]\n"; 
            foreach ($elem as $key2=>$elem2) { 
                if(is_array($elem2)) 
                { 
                    for($i=0;$i<count($elem2);$i++) 
                    { 
                        $content .= $key2."[] = \"".$elem2[$i]."\"\n"; 
                    } 
                } 
                else if($elem2=="") $content .= $key2." = \n"; 
                else $content .= $key2." = \"".$elem2."\"\n"; 
            } 
        } 
    } 
    else { 
        foreach ($assoc_arr as $key=>$elem) { 
            if(is_array($elem)) 
            { 
                for($i=0;$i<count($elem);$i++) 
                { 
                    $content .= $key."[] = \"".$elem[$i]."\"\n"; 
                } 
            } 
            else if($elem=="") $content .= $key." = \n"; 
            else $content .= $key." = \"".$elem."\"\n"; 
        } 
    } 

    if (!$handle = fopen($path, 'w')) { 
        return false; 
    }

    $success = fwrite($handle, $content);
    fclose($handle); 

    return $success; 
}

Usage:

$sampleData = array(
                'first' => array(
                    'first-1' => 1,
                    'first-2' => 2,
                    'first-3' => 3,
                    'first-4' => 4,
                    'first-5' => 5,
                ),
                'second' => array(
                    'second-1' => 1,
                    'second-2' => 2,
                    'second-3' => 3,
                    'second-4' => 4,
                    'second-5' => 5,
                ));
write_ini_file($sampleData, './data.ini', true);

Good luck!

@Dave Jarvis 2010-04-11 22:42:33

After if (!fwrite($handle, $content)) {, the file handle should be closed.

@kjetilh 2012-06-22 11:07:40

Also there's an error in the code when not using sections, the variable $key2 should be $key

@Martin Konecny 2013-05-07 20:42:27

This isn't an official solution just how your comment isn't an official comment of stack overflow.

@Tomáš Zato 2013-09-18 19:21:13

@MartinKonecny does that imply that errors are fine in unoficial solutions?

@Martin Konecny 2013-09-18 23:43:07

@TomášZato No it means he shouldn't say it's official code. It could be buggy for all I know. He grabbed it from the comments section.

@Tomáš Zato 2013-09-19 00:28:07

Sorry, I did not understand context of your comment properly the first time. Thank you for making it clear for me.

@Erik Hermansen 2014-07-09 20:07:11

Downvote. While the answer is helpful, it really would be better if the author would fix the bug in the code.

@Harri Siirak 2014-07-10 11:41:42

Fixed bugs in the example code. :)

@Erik Hermansen 2014-07-10 19:55:34

Upvote! Harri Siirak is a solid dude that improves the Internet.

@Harikrishnan 2014-08-21 10:58:51

It's nice, but when we write this to file we will loose all comments.

@extjs user 2018-01-04 09:24:16

Just wonder, if I only want to modify single value, do I have to write while file again? say I have array of ini file. $config = parse_ini_file($file, true); $config['ABC.menu']['title'] = "New title"; ..... cant I just change one value ?

@Tivie 2012-03-02 00:27:13

based on the above answers I wrote this class that might be useful. For PHP 5.3 but can be easily adapted for previous versions.

class Utils
    {
        public static function write_ini_file($assoc_arr, $path, $has_sections)
        {
            $content = '';

            if (!$handle = fopen($path, 'w'))
                return FALSE;

            self::_write_ini_file_r($content, $assoc_arr, $has_sections);

            if (!fwrite($handle, $content))
                return FALSE;

            fclose($handle);
            return TRUE;
        }

        private static function _write_ini_file_r(&$content, $assoc_arr, $has_sections)
        {
            foreach ($assoc_arr as $key => $val) {
                if (is_array($val)) {
                    if($has_sections) {
                        $content .= "[$key]\n";
                        self::_write_ini_file_r(&$content, $val, false);
                    } else {
                        foreach($val as $iKey => $iVal) {
                            if (is_int($iKey))
                                $content .= $key ."[] = $iVal\n";
                            else
                                $content .= $key ."[$iKey] = $iVal\n";
                        }
                    }
                } else {
                    $content .= "$key = $val\n";
                }
            }
        }
    }

@user1123382 2012-01-27 20:06:36

I use this and it seems to work

function listINIRecursive($array_name, $indent = 0)
{
    global $str;
    foreach ($array_name as $k => $v)
    {
        if (is_array($v))
        {
            for ($i=0; $i < $indent * 5; $i++){ $str.= " "; }
            $str.= " [$k] \r\n";
            listINIRecursive($v, $indent + 1);
        }
            else
        {
            for ($i=0; $i < $indent * 5; $i++){ $str.= " "; }
            $str.= "$k = $v \r\n";
        }
    }
 }

it returns the text to write to an .ini file

@Tivie 2012-03-02 00:20:50

Your snippet fails if $array_name contains a multi-dimensional array inside. That is, if the parent array has a depth of 3 or more.

@Dominic Rodger 2009-08-12 20:08:40

I can't vouch for how well it works, but there's some suggestions for implementing the opposite of parse_ini_file() (i.e. write_ini_file, which isn't a standard PHP function) on the documentation page for parse_ini_file.

You can use write_ini_file to send the values to a file, parse_ini_file to read them back in - modify the associative array that parse_ini_file returns, and then write the modified array back to the file with write_ini_file.

Does that work for you?

@cweiske 2011-04-18 10:54:18

PEAR has two (unit tested) packages which do the task you are longing for:

  • Config_Lite - ideal if you only want .ini files
  • Config - reads also .php and .xml files

I'd rather use well tested code than writing my own.

@Serge Wautier 2011-11-11 20:05:30

+1 for tested/supported solution

@mario-mesiti 2010-09-30 13:15:36

in this portion of code:

else { 
    foreach ($assoc_arr as $key=>$elem) { 
        if(is_array($elem)) 
        { 
            for($i=0;$i<count($elem);$i++) 
            { 
                $content .= $key2."[] = \"".$elem[$i]."\"\n"; 
            } 
        } 
        else if($elem=="") $content .= $key2." = \n"; 
        else $content .= $key2." = \"".$elem."\"\n"; 
    } 
} 

$key2 must be replaced by $key or you would find empty keys in your .ini

Related Questions

Sponsored Content

18 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

37 Answered Questions

[SOLVED] Deleting an element from an array in PHP

  • 2008-12-15 20:28:55
  • Ben
  • 2438740 View
  • 2354 Score
  • 37 Answer
  • Tags:   php arrays unset

34 Answered Questions

[SOLVED] Reference - What does this error mean in PHP?

7 Answered Questions

[SOLVED] How does PHP 'foreach' actually work?

16 Answered Questions

[SOLVED] Why shouldn't I use mysql_* functions in PHP?

  • 2012-10-12 13:18:39
  • Madara Uchiha
  • 211737 View
  • 2428 Score
  • 16 Answer
  • Tags:   php mysql database

14 Answered Questions

[SOLVED] Why would one omit the close tag?

28 Answered Questions

[SOLVED] How can I prevent SQL injection in PHP?

30 Answered Questions

[SOLVED] How do you parse and process HTML/XML in PHP?

10 Answered Questions

[SOLVED] What is the easiest way to parse an INI file in Java?

  • 2008-10-10 09:20:55
  • Mario Ortegón
  • 133877 View
  • 100 Score
  • 10 Answer
  • Tags:   java parsing ini

16 Answered Questions

[SOLVED] Reading/writing an INI file

  • 2008-10-20 09:37:22
  • zendar
  • 449547 View
  • 246 Score
  • 16 Answer
  • Tags:   c# .net ini

Sponsored Content