Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

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
  1. How do I read the value belonging to "lu_link" or "footerbg"?
  2. How to I write a new value for these places?
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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("
", $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);
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...