note 75354 deleted from function.parse-ini-file by nlopess

From: Date: Sun, 27 May 2007 19:03:35 +0000
Subject: note 75354 deleted from function.parse-ini-file by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-126969@lists.php.net to get a copy of this message
Note Submitter: Mildred ---- I wrote few functions to work with ini files. The function make_ini_file($array, &$errors) The function read_ini($file) The function prepare_ini($array, $maxdepth=NULL) The function make_ini_file($array, &$errors) It returns a string in a valid ini format (that can be parsed with parse_ini_file). It takes the array to be used to create the ini file (-in the same format as the array returned by parse_ini_file) and an array reference where errors will be added when happening (for example when there are unserialisable values) <?php function make_ini_file($assoc_array, &$errors){ $content = ''; $sections = ''; if(!is_array($errors)) $errors = array(); $maxkeylen = make_ini_file__maxkeylen($assoc_array); foreach ($assoc_array as $key => $item){ if (is_array($item)) { $sections .= "\n[$key]\n"; $maxkeylen2 = make_ini_file__maxkeylen($item); foreach ($item as $key2 => $item2) { $sections .= make_ini_file__pair($key, $key2, $item2, $maxkeylen2, $errors); } } else { $content .= make_ini_file__pair(false, $key, $item, $maxkeylen, $errors); } } return $content . $sections; } function make_ini_file__pair($section, $key, $item, $keylen, &$errors){ if(is_bool($item)) $item = $item ? "yes" : "no" ; elseif($item===true) $item = "yes"; elseif($item===false) $item = "no"; elseif(is_null($item)) $item = "null"; elseif(is_numeric($item)) $item = sprintf("%g", $item); elseif(is_string($item)){ if( ereg('^[a-zA-Z0-9_\.-]+$', $item) and !in_array($item, array('yes', 'no', 'true', 'false', 'null'))) { }else{ $item = str_replace("\"", '\\"', $item); $item = str_replace("\n", '\\n', $item); $item = sprintf('"%s"', $item); } }else{ $errors[] = "Unserializable value for key `$key'". ($section ? "in section `$section'." : "."); return ""; } if(is_int($keylen)) $key = str_pad($key, $keylen); return "$key = $item\n"; } function make_ini_file__maxkeylen($arr){ $len = 0; foreach($arr as $key=>$val){ if(is_string($key)) $len = max(strlen($key), $len); } return $len; } // kate: indent-width 4; tab-width 8; space-indent on; // kate: replace-tabs off; remove-trailing-space on; ?>

« previous php.notes (#126969) next »