create ini file, write values in PHP - php

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.

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!

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.

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?

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

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";
}
}
}
}

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

Related

php, how can I update ini file? [duplicate]

I've been looking around the official php documentation but I'm unable to find what I'm looking for.
http://php.net/manual/en/function.parse-ini-file.php
I just want a function to edit and read the value from the php ini file, for instance,
[default_colors]
sitebg = #F8F8F8
footerbg = #F8F8F8
link = #F8F8F8
url = #F8F8F8
bg = #F8F8F8
text = #F8F8F8
border = #F8F8F8
lu_link = #F8F8F8
lu_url = #F8F8F8
lu_bg = #F8F8F8
lu_text = #f505f5
lu_border = #F8F8F8
How do I read the value belonging to "lu_link" or "footerbg"?
How to I write a new value for these places?
You can simply use parse_ini_file with PHP4/5.
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);
Here is the doc: http://php.net/manual/en/function.parse-ini-file.php
To write back an array of objects back to the ini file, use below as a very fast & easy solution:
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
The PEAR Config_Lite package can do almost all the work (both reading and writing) for you super-easily. Check it out here: http://pear.php.net/package/Config_Lite
How about this:
$key='option';
$val='1.2.3.4.5';
system("sed -ie 's/\({$key}=\)\(.*\)/\1{$val}/' file.in");
Below is an implementation of write_ini_file() which PHP is currently lacking, it will create an almost identical (except comments) of the input:
Supports cross platform (PHP_EOL) new lines added between sections.
Handles both index and key value arrays.
Handles CONSTANT style values.
And file locking to stay consistent.
Source
<?php
if (!function_exists('write_ini_file')) {
/**
* Write an ini configuration file
*
* #param string $file
* #param array $array
* #return bool
*/
function write_ini_file($file, $array = []) {
// check first argument is string
if (!is_string($file)) {
throw new \InvalidArgumentException('Function argument 1 must be a string.');
}
// check second argument is array
if (!is_array($array)) {
throw new \InvalidArgumentException('Function argument 2 must be an array.');
}
// process array
$data = array();
foreach ($array as $key => $val) {
if (is_array($val)) {
$data[] = "[$key]";
foreach ($val as $skey => $sval) {
if (is_array($sval)) {
foreach ($sval as $_skey => $_sval) {
if (is_numeric($_skey)) {
$data[] = $skey.'[] = '.(is_numeric($_sval) ? $_sval : (ctype_upper($_sval) ? $_sval : '"'.$_sval.'"'));
} else {
$data[] = $skey.'['.$_skey.'] = '.(is_numeric($_sval) ? $_sval : (ctype_upper($_sval) ? $_sval : '"'.$_sval.'"'));
}
}
} else {
$data[] = $skey.' = '.(is_numeric($sval) ? $sval : (ctype_upper($sval) ? $sval : '"'.$sval.'"'));
}
}
} else {
$data[] = $key.' = '.(is_numeric($val) ? $val : (ctype_upper($val) ? $val : '"'.$val.'"'));
}
// empty line
$data[] = null;
}
// open file pointer, init flock options
$fp = fopen($file, 'w');
$retries = 0;
$max_retries = 100;
if (!$fp) {
return false;
}
// loop until get lock, or reach max retries
do {
if ($retries > 0) {
usleep(rand(1, 5000));
}
$retries += 1;
} while (!flock($fp, LOCK_EX) && $retries <= $max_retries);
// couldn't get the lock
if ($retries == $max_retries) {
return false;
}
// got lock, write data
fwrite($fp, implode(PHP_EOL, $data).PHP_EOL);
// release lock
flock($fp, LOCK_UN);
fclose($fp);
return true;
}
}
Example input .ini file (taken from http://php.net/manual/en/function.parse-ini-file.php)
; This is a sample configuration file
; Comments start with ';', as in php.ini
[first_section]
one = 1
five = 5
animal = BIRD
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"
[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"
urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"
Example usage:
// load ini file values into array
$config = parse_ini_file('config.ini', true);
// add some additional values
$config['main']['foobar'] = 'baz';
$config['main']['const']['a'] = 'UPPERCASE';
$config['main']['const']['b'] = 'UPPER_CASE WITH SPACE';
$config['main']['array'][] = 'Some Value';
$config['main']['array'][] = 'ADD';
$config['third_section']['urls']['docs'] = 'http://php.net';
// write ini file
write_ini_file('config.ini', $config);
Resulting .ini file:
[first_section]
one = 1
five = 5
animal = BIRD
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"
[third_section]
phpversion[] = 5.0
phpversion[] = 5.1
phpversion[] = 5.2
phpversion[] = 5.3
urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"
urls[docs] = "http://php.net"
[main]
foobar = "baz"
const[a] = UPPERCASE
const[b] = "UPPER_CASE WITH SPACE"
array[] = "Some Value"
array[] = ADD
Here's a functional version that creates a string that can be written to a file.
function IniAsStr(array $a) : string
{
return array_reduce(array_keys($a), function($str, $sectionName) use ($a) {
$sub = $a[$sectionName];
return $str . "[$sectionName]" . PHP_EOL .
array_reduce(array_keys($sub), function($str, $key) use($sub) {
return $str . $key . '=' . $sub[$key] . PHP_EOL;
}) . PHP_EOL;
});
}
Here is your function to read and write INI files with a category option!
If you provide multi dimensional array, you will have category in your INI file.
Or basic array will allow you to read and write data fast.
See the comments and example below for details:
### PHP write_ini_file function to use with parse_ini_file: (choose one of the two example arrays below...)
$array = array('category' => array('color' => 'blue', 'size' => 'large'));
// $array = array('color' => 'red', 'size' => 'small');
function write_ini_file($array, $path) {
unset($content, $arrayMulti);
# See if the array input is multidimensional.
foreach($array AS $arrayTest){
if(is_array($arrayTest)) {
$arrayMulti = true;
}
}
# Use categories in the INI file for multidimensional array OR use basic INI file:
if ($arrayMulti) {
foreach ($array 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 ($array 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";
}
}
}
if (!$handle = fopen($path, 'w')) {
return false;
}
if (!fwrite($handle, $content)) {
return false;
}
fclose($handle);
return true;
}
write_ini_file($array,'./data.ini');
$readData = parse_ini_file('./data.ini',true);
print_r($readData);

iCal decoder function returning blank array in PHP

I followed a tutorial to import iCal data into my website using PHP. For some reason, the array doesn't seem to include any data even though the feed shows info in a feed validator website. Can anyone take a look at the decoder function? I'm guessing there's a simple reason for this but I'm a novice.
public function iCalDecoder($file) {
$ical = file_get_contents('https://www.google.com/calendar/ical/689afn1fkt0cb59kame9bg56mg%40group.calendar.google.com/private-584915c30803f5ad6c548f021e84f836/basic.ics');
preg_match_all('/(BEGIN:VEVENT.*?END:VEVENT)/si', $ical, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
$tmpbyline = explode("rn", $result[0][$i]);
foreach ($tmpbyline as $item) {
$tmpholderarray = explode(":",$item);
if (count($tmpholderarray) >1) {
$majorarray[$tmpholderarray[0]] = $tmpholderarray[1];
}
}
if (preg_match('/DESCRIPTION:(.*)END:VEVENT/si', $result[0][$i], $regs)) {
$majorarray['DESCRIPTION'] = str_replace(" ", " ", str_replace("rn", "", $regs[1]));
}
$icalarray[] = $majorarray;
unset($majorarray);
}
return $icalarray;
}
found another function that actually works. Thanks for looking and I hope this helps someone in the future!
function icsToArray($paramUrl) {
$icsFile = file_get_contents($paramUrl);
$icsData = explode("BEGIN:", $icsFile);
foreach($icsData as $key => $value) {
$icsDatesMeta[$key] = explode("\n", $value);
}
foreach($icsDatesMeta as $key => $value) {
foreach($value as $subKey => $subValue) {
if ($subValue != "") {
if ($key != 0 && $subKey == 0) {
$icsDates[$key]["BEGIN"] = $subValue;
} else {
$subValueArr = explode(":", $subValue, 2);
$icsDates[$key][$subValueArr[0]] = $subValueArr[1];
}
}
}
}
return $icsDates;
}

Export mysql data as CSV in php

In my code, I need to preserve all commas in each fields from the mysql table in CSV Export...
For this I used the double quotes to all fields. This code is perfectly running in the Linux System.. While running the same code in windows, double quotes also displaying in Exported CSV file.. What is the problem in this? can anyone tell me why it is happening like this?
function arrayToCSV($array, $header_row = true, $col_sep = ",", $row_sep = "\n", $qut = '"',$pgeTyp ="")
{
/*col_sep =htmlentities($col_sep);
$row_sep =htmlentities($row_sep);
$qut =htmlentities($qut);*/
if (!is_array($array) or !is_array($array[0])) return false;
//Header row.
if ($header_row)
{
foreach ($array[0] as $key => $val)
{
//Escaping quotes.
$key = str_replace($qut, "$qut$qut", $key);
$output .= $col_sep.$qut.$key.$qut;
}
$output = substr($output, 1)."\n".$row_sep;
}
//Data rows.
foreach ($array as $key => $val)
{
$tmp = '';
foreach ($val as $cell_key => $cell_val)
{
if($pgeTyp!="twitter" && $pagTyp!="jigsaw" && $pgeTyp=="")
$timeValue = #checkTimeStamp($cell_val);
else $timeValue = '';
if($timeValue=="True")
{
$cell_val = str_replace($qut, "$qut$qut", convert_time_zone($cell_val,'d-M-y h:i:s'));
}
else
{
$cell_val = str_replace($qut, "$qut$qut", $cell_val);
}
$tmp .= $col_sep.$qut.$cell_val.$qut;
}
$output .= substr($tmp, 1).$row_sep;
}
return $output;
}
Function call is,
$dbResult1[] =array('url_twitter_userid' => $selecttwittermainFtch['url_twitter_userid'],'url_tweet_name' => "$url_tweet_name",'url_twitter_uname' => "$url_twitter_uname",'url_twitter_url' => $selecttwittermainFtch['url_twitter_url'],'url_twitter_location' => "$url_twitter_location",'url_twitter_followers' => $selecttwittermainFtch['url_twitter_followers'],'url_twitter_following' => $selecttwittermainFtch['url_twitter_following'],'url_modified_on' => $modifiedon);
echo arrayToCSV($dbResult1, true, ", ", "\n", '','twitter');
Try this:
function sqlQueryToCSV($filename, $query)
{
$result = mysql_query($query);
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen(mysql_real_escape_string(getcwd().'\\'.$filename), 'w');
if ($fp) {
fputcsv($fp, $headers);
while ($row = mysql_fetch_array($result)) {
$arrayValues = array();
foreach ($headers as $header)
{
$arrayValues[] = $row[$header];
}
fputcsv($fp, $arrayValues);
}
}
fclose($fp);
}
Source: http://forums.exchangecore.com/topic/907-function-to-convert-mysql-query-to-csv-file-with-php/
When you are opening it in Windows with whatever program (Guessing Excel), you should be able to specify what characters you use to delimit/surround the fields. It's probably just assuming that you are just wanting to use commas to separate but ignoring the double quotes surrounding them.

How to read and write to an ini file with PHP

I've been looking around the official php documentation but I'm unable to find what I'm looking for.
http://php.net/manual/en/function.parse-ini-file.php
I just want a function to edit and read the value from the php ini file, for instance,
[default_colors]
sitebg = #F8F8F8
footerbg = #F8F8F8
link = #F8F8F8
url = #F8F8F8
bg = #F8F8F8
text = #F8F8F8
border = #F8F8F8
lu_link = #F8F8F8
lu_url = #F8F8F8
lu_bg = #F8F8F8
lu_text = #f505f5
lu_border = #F8F8F8
How do I read the value belonging to "lu_link" or "footerbg"?
How to I write a new value for these places?
You can simply use parse_ini_file with PHP4/5.
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);
Here is the doc: http://php.net/manual/en/function.parse-ini-file.php
To write back an array of objects back to the ini file, use below as a very fast & easy solution:
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
The PEAR Config_Lite package can do almost all the work (both reading and writing) for you super-easily. Check it out here: http://pear.php.net/package/Config_Lite
How about this:
$key='option';
$val='1.2.3.4.5';
system("sed -ie 's/\({$key}=\)\(.*\)/\1{$val}/' file.in");
Below is an implementation of write_ini_file() which PHP is currently lacking, it will create an almost identical (except comments) of the input:
Supports cross platform (PHP_EOL) new lines added between sections.
Handles both index and key value arrays.
Handles CONSTANT style values.
And file locking to stay consistent.
Source
<?php
if (!function_exists('write_ini_file')) {
/**
* Write an ini configuration file
*
* #param string $file
* #param array $array
* #return bool
*/
function write_ini_file($file, $array = []) {
// check first argument is string
if (!is_string($file)) {
throw new \InvalidArgumentException('Function argument 1 must be a string.');
}
// check second argument is array
if (!is_array($array)) {
throw new \InvalidArgumentException('Function argument 2 must be an array.');
}
// process array
$data = array();
foreach ($array as $key => $val) {
if (is_array($val)) {
$data[] = "[$key]";
foreach ($val as $skey => $sval) {
if (is_array($sval)) {
foreach ($sval as $_skey => $_sval) {
if (is_numeric($_skey)) {
$data[] = $skey.'[] = '.(is_numeric($_sval) ? $_sval : (ctype_upper($_sval) ? $_sval : '"'.$_sval.'"'));
} else {
$data[] = $skey.'['.$_skey.'] = '.(is_numeric($_sval) ? $_sval : (ctype_upper($_sval) ? $_sval : '"'.$_sval.'"'));
}
}
} else {
$data[] = $skey.' = '.(is_numeric($sval) ? $sval : (ctype_upper($sval) ? $sval : '"'.$sval.'"'));
}
}
} else {
$data[] = $key.' = '.(is_numeric($val) ? $val : (ctype_upper($val) ? $val : '"'.$val.'"'));
}
// empty line
$data[] = null;
}
// open file pointer, init flock options
$fp = fopen($file, 'w');
$retries = 0;
$max_retries = 100;
if (!$fp) {
return false;
}
// loop until get lock, or reach max retries
do {
if ($retries > 0) {
usleep(rand(1, 5000));
}
$retries += 1;
} while (!flock($fp, LOCK_EX) && $retries <= $max_retries);
// couldn't get the lock
if ($retries == $max_retries) {
return false;
}
// got lock, write data
fwrite($fp, implode(PHP_EOL, $data).PHP_EOL);
// release lock
flock($fp, LOCK_UN);
fclose($fp);
return true;
}
}
Example input .ini file (taken from http://php.net/manual/en/function.parse-ini-file.php)
; This is a sample configuration file
; Comments start with ';', as in php.ini
[first_section]
one = 1
five = 5
animal = BIRD
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"
[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"
urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"
Example usage:
// load ini file values into array
$config = parse_ini_file('config.ini', true);
// add some additional values
$config['main']['foobar'] = 'baz';
$config['main']['const']['a'] = 'UPPERCASE';
$config['main']['const']['b'] = 'UPPER_CASE WITH SPACE';
$config['main']['array'][] = 'Some Value';
$config['main']['array'][] = 'ADD';
$config['third_section']['urls']['docs'] = 'http://php.net';
// write ini file
write_ini_file('config.ini', $config);
Resulting .ini file:
[first_section]
one = 1
five = 5
animal = BIRD
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"
[third_section]
phpversion[] = 5.0
phpversion[] = 5.1
phpversion[] = 5.2
phpversion[] = 5.3
urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"
urls[docs] = "http://php.net"
[main]
foobar = "baz"
const[a] = UPPERCASE
const[b] = "UPPER_CASE WITH SPACE"
array[] = "Some Value"
array[] = ADD
Here's a functional version that creates a string that can be written to a file.
function IniAsStr(array $a) : string
{
return array_reduce(array_keys($a), function($str, $sectionName) use ($a) {
$sub = $a[$sectionName];
return $str . "[$sectionName]" . PHP_EOL .
array_reduce(array_keys($sub), function($str, $key) use($sub) {
return $str . $key . '=' . $sub[$key] . PHP_EOL;
}) . PHP_EOL;
});
}
Here is your function to read and write INI files with a category option!
If you provide multi dimensional array, you will have category in your INI file.
Or basic array will allow you to read and write data fast.
See the comments and example below for details:
### PHP write_ini_file function to use with parse_ini_file: (choose one of the two example arrays below...)
$array = array('category' => array('color' => 'blue', 'size' => 'large'));
// $array = array('color' => 'red', 'size' => 'small');
function write_ini_file($array, $path) {
unset($content, $arrayMulti);
# See if the array input is multidimensional.
foreach($array AS $arrayTest){
if(is_array($arrayTest)) {
$arrayMulti = true;
}
}
# Use categories in the INI file for multidimensional array OR use basic INI file:
if ($arrayMulti) {
foreach ($array 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 ($array 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";
}
}
}
if (!$handle = fopen($path, 'w')) {
return false;
}
if (!fwrite($handle, $content)) {
return false;
}
fclose($handle);
return true;
}
write_ini_file($array,'./data.ini');
$readData = parse_ini_file('./data.ini',true);
print_r($readData);

problem with parse_ini_file

I'm using parse_ini_file() to read an ini file that has this line:
[admin]
hide_fields[] = ctr_ad_headerImg
the problem is that it outputs it like,
[admin]
hide_fields = Array
can someone help me out? how do I read "hide_fields[]" like a string?
Best Regards
Joricam
My code is:
$ini_array = parse_ini_file($config_path, true);
//print_r($ini_array);
//echo $ini_array["default_colors"]["sitebg"];
$ini_array["default_colors"]["sitebg"]="#000000";
write_php_ini($ini_array,$config_path);
Functions that Im using:
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : ''.$sval.'');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : ''.$val.'');
}
safefilerewrite($file, implode("\r\n", $res));
}
//////
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime();
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime()-$startTime) < 1000));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
Parse_ini_file() does handle such identifiers. It correctly converts them into arrays on reading the ini file:
print_r(parse_ini_string("hide_fields[] = ctr_ad_headerImg"));
Will generate:
Array
(
[hide_fields] => Array
(
[0] => ctr_ad_headerImg
)
The entry can be accessed as $cfg["hide_fields"][0] in PHP. The problem is that the ini file output function you have chosen this time does not understand array attributes.
Since you are probably interested in workarounds instead of using an appropriate tool, apply this conversion loop on your ini data:
// foreach ($sections ...) maybe
foreach ($cfg as $key=>$value) {
if (is_array($value)) {
foreach ($value as $i=>$v) {
$cfg["$key"."[$i]"] = $v;
}
unset($cfg[$key]);
}
}
And save it afterwards.
Edited code
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) {
if (is_array($sval)) {
foreach ($sval as $i=>$v) {
$res[] = "{$skey}[$i] = $v";
}
}
else {
$res[] = "$skey = $sval";
}
}
}
else $res[] = "$key = $val";
}
safefilerewrite($file, implode("\r\n", $res));
}
//////
function safefilerewrite($fileName, $dataToSave)
{
file_put_contents($fileName, $dataToSave, LOCK_EX);
}

Categories