我需要能够编辑.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*$/', $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");
我没有在Zend组件框架中使用过配置写入器,但我使用过配置读取器,它非常可靠。值得一试。
editconfigini.php
,但它忽略了配置文件中的节(sections),只关心特定的键=值(key=value)格式。 - mario