note 43382 deleted from function.parse-ini-file by danbrown
| From: | danbrown@php.net | Date: | Sun, 23 Jan 2011 17:17:24 +0000 |
| Subject: | note 43382 deleted from function.parse-ini-file by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176179@lists.php.net to get a copy of this message | ||
Note Submitter: Jomel (k95vz5f02 AT sneakemail DOT com)
----
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.