[eluser]mezoni[/eluser]
Example.
Code:
$this->load->helper('config');
$elements['test']['index'] = 'Index"';
$elements['test']['simple'] = "Simple'";
$elements['test']['null'] = null;
$elements['test']['true'] = TRUe;
$elements['test']['num'] = 1.11111111111111111111;
$elements['test']['0']['1'] = '1';
$elements['test']['0']['2'] = '2';
$elements['mest']['8']['9'] = '3';
$elements['rest'] = '4';
$section = 'myconfig';
config_write('myconfig', $section, $elements);
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function config_to_lines($elements, $section, $keys, $level, &$result)
{
if(!is_array($elements))
{
return;
}
foreach($elements as $key => $val)
{
if($level == 0)
{
$keys = '';
}
if(is_string($key))
{
$q = 0;
if(strrchr($key, "'") !== FALSE)
{
$q = 1;
}
if(strrchr($key, '"') !== FALSE)
{
$q += 2;
}
switch($q)
{
case 1:
$key = '"' . $key . '"';
break;
case 3:
$key = "'" . addslashes($key) . "'";
break;
default:
$key = "'" . $key . "'";
}
}
else
{
$key = "'" . $key . "'";
}
$key = '[' . $key . ']';
if(is_array($val))
{
config_to_lines($val, $section, $keys . $key, $level + 1, $result);
continue;
}
if(!empty($section))
{
$str = '$config[' . "'" . $section . "'" . ']';
}
else
{
$str = '$config';
}
if(is_string($val))
{
$q = 0;
if(strrchr($val, "'") !== FALSE)
{
$q = 1;
}
if(strrchr($val, '"') !== FALSE)
{
$q += 2;
}
switch($q)
{
case 1:
$v = '"' . $val . '"';
break;
case 3:
$v = "'" . addslashes($val) . "'";
break;
default:
$v = "'" . $val . "'";
}
}
elseif(is_numeric($val))
{
$v = $val;
}
elseif(is_bool($val))
{
$v = $val ? 'TRUE' : 'FALSE';
}
elseif(is_null($val))
{
$v = 'NULL';
}
elseif(is_object($val))
{
$v = serialize($val);
}
else
{
$v = $val;
}
$str .= $keys . $key . ' = ' . $v . ';';
$result[] = $str;
}
}
function config_write($file, $section, $data)
{
$section = trim($section);
$lines[] = "<?php if (!defined('BASEPATH')) exit('No direct script access allowed');";
$lines[] = "";
if(is_array($data))
{
config_to_lines($data, $section, '', 0, $lines);
}
$lines[] = "";
$lines[] = "?>";
$filepath = APPPATH . 'config/' . $file . EXT;
$fp = fopen($filepath, 'w');
flock($fp, LOCK_EX);
foreach($lines as $line)
{
fputs($fp, $line . "\n");
}
flock($fp, LOCK_UN);
fclose($fp);
@chmod($filepath, 0666);
}
?>