操作.ini文件的好PHP类

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了操作.ini文件的好PHP类脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要能够编辑.ini文件(我正在用parse_ini_file读取),但是这样就保留了注释和格式(换行符,缩进).

知道任何对这类东西有优秀和优化功能的优秀课程吗?

您可以尝试从此开始,它会读取ini文件,并在写入时保留设置,您必须扩展它以支持添加新条目:
class ini {
    PRotected $lines;

    public function read($file) {
        $this->lines = array();

        $section = '';

        foreach(file($file) as $line) {
            // comment or whITespace
            if(preg_match('/^\s*(;.*)?$/',$line)) {
                $this->lines[] = array('tyPE' => 'comment','data' => $line);
            // section
            } elseif(preg_match('/\[(.*)\]/',$line,$match)) {
                $section = $match[1];
                $this->lines[] = array('type' => 'section','data' => $line,'section' => $section);
            // entry
            } elseif(preg_match('/^\s*(.*?)\s*=\s*(.*?)\s*$/',$match)) {
                $this->lines[] = array('type' => 'entry','section' => $section,'key' => $match[1],'value' => $match[2]);
            }
        }
    }

    public function get($section,$key) {
        foreach($this->lines as $line) {
            if($line['type'] != 'entry') continue;
            if($line['section'] != $section) continue;
            if($line['key'] != $key) continue;
            return $line['value'];
        }

        throw new Exception('Missing Section or Key');
    }

    public function set($section,$key,$value) {
        foreach($this->lines as &$line) {
            if($line['type'] != 'entry') continue;
            if($line['section'] != $section) continue;
            if($line['key'] != $key) continue;
            $line['value'] = $value;
            $line['data'] = $key . " = " . $value . "\r\n";
            return;
        }

        throw new Exception('Missing Section or Key');
    }

    public function write($file) {
        $fp = fopen($file,'w');

        foreach($this->lines as $line) {
            fwrite($fp,$line['data']);
        }

        fclose($fp);
    }
}

$ini = new ini();
$ini->read("C:\\PHP.ini");
$ini->set('PHP','engine','Off');
echo $ini->get('PHP','engine');
$ini->write("C:\\PHP.ini");

脚本宝典总结

以上是脚本宝典为你收集整理的操作.ini文件的好PHP类全部内容,希望文章能够帮你解决操作.ini文件的好PHP类所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。