note 43382 added to function.parse-ini-file

From: Date: Sat, 19 Jun 2004 12:02:14 +0000
Subject: note 43382 added to function.parse-ini-file
Groups: php.notes 
Request: Send a blank email to php-notes+get-71329@lists.php.net to get a copy of this message
based entirely on LIU student's code (thanks), here's a write_ini_file function you can use whether or not the array you are writing is sorted into sections. It is designed so that $arr1 equals $arr2 in both the cases below, using sections: <?php $arr1 = parse_ini_file($filename, true); write_ini_file(parse_ini_file($filename, true), $filename, true); $arr2 = parse_ini_file($filename, true); ?> and without sections: <?php $arr1 = parse_ini_file($filename); write_ini_file(parse_ini_file($filename), $filename); $arr2 = parse_ini_file($filename); ?> i.e. files written using write_ini_file will be semantically identical (as far as parse_ini_file can see) to the originals. Here is the code: <?php if (!function_exists('write_ini_file')) { 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) { $content .= $key2." = \"".$elem2."\"\n"; } } } else { foreach ($assoc_arr as $key=>$elem) { $content .= $key." = \"".$elem."\"\n"; } } if (!$handle = fopen($path, 'w')) { return false; } if (!fwrite($handle, $content)) { return false; } fclose($handle); return true; } } ?> Incidentally I wrapped it inside an if (!function_exists(...)) block so you can just put this wherever it's needed in your code without having to worry about it being declared several times. Warning: if you read an ini file then write it using <?php write_ini_file(parse_ini_file($fname), $fname); ?>, any sections will obviously be lost. Note also: unquoted values will be quoted and varname=true will become varname = "1" when writing an ini file back to itself using <?php write_ini_file(parse_ini_file($fname, true), $fname, true); ?> or <?php write_ini_file(parse_ini_file($fname), $fname); ?>. This should make no difference, but it might cause the types of the variables to change in case you plan on using === or !== comparisions. ---- Manual Page -- http://www.php.net/manual/en/function.parse-ini-file.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+43382 Delete -- http://master.php.net/manage/user-notes.php?action=delete+43382&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+43382&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#71329) next »