INI Files Handler

1 篇文章 / 0 new
author
INI Files Handler
/**
 * INI file handler class
 * Coded by: Jos?Silva, Jr
 * e-mail: josesilvajunior at gmail dot com
 * Date: jun 7 2012
 *
 * Usage:
 * $ini = new ini('test.ini');
 * $ini->get('SOME_GROUP', 'SOME_VAR'); // return false if the group or variable isn't found
 * $ini->set('SOME_GROUP', 'SOME_VAR', 'SOME_VALUE');
 * $ini->delGroup('SOME_GROUP');
 * $ini->del('SOME_GROUP', 'SOME_VAR');
 * $ini->save();
 *
 *  若有異動釋放前必須呼叫 save()
 */
 
class ini {
    var $ini_file;
    var $content;
 
    function __construct($if) {
        if(! file_exists($if)) {
            $hd = fopen($if, 'w');
 
            fclose($if);
        }
 
        $this->ini_file = $if;
        $this->content  = array();
        $this->load();
    }
 
    function load() {
        $this->content = parse_ini_file($this->ini_file, true);
    }
 
    function get($g, $v) {
        if(key_exists($v, $this->content[$g]))
            return $this->content[$g][$v];
        else
            return false;
    }
 
    function set($g, $v, $u) {
        $this->content[$g][$v] = $u;
    }
 
    function delGroup($g) {
        unset($this->content[$g]);
    }
 
    function del($g, $v) {
        unset($this->content[$g][$v]);
    }
 
    function save() {
        $hd = fopen($this->ini_file, 'w');
 
        foreach($this->content as $kgroup => $group) {
            fwrite($hd, '[' . $kgroup . ']' . "\r\n");
 
            foreach($group as $key => $var) {
                fwrite($hd, $key . ' = ' . $var . "\r\n");
            }
 
            fwrite($hd, "\r\n");
        }
 
        fclose($hd);
    }
 
}
Free Web Hosting