I need to read a ini file, modify some values in some
sections, and save it. But the important thing is, i want to
keep all the comments, the new lines in the right order. So
i modified function parse_ini_file_quotes_safe and
write_ini_file.
I think they work fine.
function read_ini_file($f, &$r)
{
$null = "";
$r=$null;
$first_char = "";
$sec=$null;
$comment_chars=";#";
$num_comments = "0";
$num_newline = "0";
//Read to end of file with the newlines still attached
into $f
$f = file($f);
if ($f === false) {
return -2;
}
// Process all lines from 0 to count($f)
for ($i=0; $i< count($f); $i++)
{
$w= trim($f[$i]);
$first_char = substr($w,0,1);
if ($w)
{
if (( substr($w,0,1)=="[") and ( substr($w,-1,1))=="]") {
$sec= substr($w,1, strlen($w)-2);
$num_comments = 0;
$num_newline = 0;
}
else if ((stristr($comment_chars, $first_char) == true))
{
$r[$sec]["Comment_".$num_comments]=$w;
$num_comments = $num_comments +1;
}
else {
// Look for the = char to allow us to split the section
into key and value
$w= explode("=",$w);
$k= trim($w[0]);
unset($w[0]);
$v= trim( implode("=",$w));
// look for the new lines
if (( substr($v,0,1)==""") and ( substr($v,-1,1)==""")) {
$v= substr($v,1, strlen($v)-2);
}
$r[$sec][$k]=$v;
}
}
else {
$r[$sec]["Newline_".$num_newline]=$w;
$num_newline = $num_newline +1;
}
}
return 1;
}
function write_ini_file($path, $assoc_arr) {
$content = "";
foreach ($assoc_arr as $key=>$elem) {
if (is_array($elem)) {
if ($key != '') {
$content .= "[".$key."]rn";
}
foreach ($elem as $key2=>$elem2) {
if ($this->beginsWith($key2,'Comment_') == 1
&& $this->beginsWith($elem2,';')) {
$content .= $elem2."rn";
}
else if ($this->beginsWith($key2,'Newline_') == 1
&& ($elem2 == '')) {
$content .= $elem2."rn";
}
else {
$content .= $key2." =
".$elem2."rn";
}
}
}
else {
$content .= $key." =
".$elem."rn";
}
}
if (!$handle = fopen($path, 'w')) {
return -2;
}
if (!fwrite($handle, $content)) {
return -2;
}
fclose($handle);
return 1;
}
function beginsWith( $str, $sub ) {
return ( substr( $str, 0, strlen( $sub ) ) === $sub );
}
----
Server IP: 69.147.83.197
Probable Submitter: 210.245.51.55
----
Manual Page -- http://www.php.net/manual/en/function.parse-ini-file.php
Edit -- https://master
.php.net/note/edit/78060
Del: integrated -- h
ttps://master.php.net/note/delete/78060/integrated
Del: useless -- http
s://master.php.net/note/delete/78060/useless
Del: bad code -- htt
ps://master.php.net/note/delete/78060/bad+code
Del: spam -- https:/
/master.php.net/note/delete/78060/spam
Del: non-english --
https://master.php.net/note/delete/78060/non-english
Del: in docs -- http
s://master.php.net/note/delete/78060/in+docs
Del: other reasons-- https://mast
er.php.net/note/delete/78060
Reject -- https://mast
er.php.net/note/reject/78060
Search -- https://
master.php.net/manage/user-notes.php
--
PHP Notes Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub
.php
|