php ini文件操作类,操作.ini文件的好PHP类

您可以尝试从此开始,它会读取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*$/', $line, $match)) {

$this->lines[] = array('type' => 'entry', 'data' => $line, '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");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值