rik72/inifile

类,用于读取和修改ini文件,同时保留注释和空行

v3.3.6 2021-03-13 11:15 UTC

README

一些类,用于读取和修改ini文件,同时保留注释和空行。

它们支持章节和数组值。您还可以合并章节,合并两个ini文件,以及重命名某些值或章节。

安装

您可以从Composer安装它。在您的项目中

composer require "jelix/inifile"

用法

\Jelix\IniFile\IniModifier类允许读取ini文件,修改其内容(包括注释),并保存它,同时保留空行。

不要使用此类仅读取内容。为此,请使用\Jelix\IniFile\Utilparse_ini_file(),它们更高效、性能更好。

$ini = new \Jelix\IniFile\IniModifier('myfile.ini');

// setting a parameter.  (section_name is optional)
$ini->setValue('parameter_name', 'value', 'section_name');

// retrieve a parameter value. (section_name is optional)
$val = $ini->getValue('parameter_name', 'section_name');

// remove a parameter
$ini->removeValue('parameter_name', 'section_name');

// setting a comment (in the line preceding the parameter) - the leading ';'
// can be omitted or included in the comment line, if missing will be added
$ini->setComments('parameter_name', '; single-line comment text', 'section_name');

// setting a multi-line comment (in the lines preceding the parameter)
$ini->setComments('parameter_name', [ 'first line', 'second line' ], 'section_name');

// remove all comment lines preceding a parameter
$ini->removeComments('parameter_name', 'section_name');

// save into file
$ini->save();
$ini->saveAs('otherfile.ini');

// importing an ini file into an other
$ini2 = new \Jelix\IniFile\IniModifier('myfile2.ini');
$ini->import($ini2);
$ini->save();

// merging two section: merge sectionSource into sectionTarget and then 
// sectionSource is removed
$ini->mergeSection('sectionSource', 'sectionTarget');

它支持将参数值解析为PHP类型(字符串、数字、布尔值)以及

它还支持数组值(索引或关联)如下

foo[]=bar
foo[]=baz
assoc[key1]=car
assoc[otherkey]=bus

然后在PHP中

$ini = new \Jelix\IniFile\IniModifier('myfile.ini');

$val = $ini->getValue('foo'); // array('bar', 'baz');
$val = $ini->getValue('assoc'); // array('key1'=>'car', 'otherkey'=>'bus');

$ini->setValue('foo', 'other value', 0, '');
$val = $ini->getValue('foo'); // array('bar', 'baz', 'other value');

$ini->setValue('foo', 'five', 0, 5);
$val = $ini->getValue('foo'); // array('bar', 'baz', 'other value', 5 => 'five');

$ini->setValue('assoc', 'other value', 0, 'ov');
$val = $ini->getValue('assoc'); // array('key1'=>'car', 'otherkey'=>'bus', 'ov'=>'other value');

保存后,ini内容是

foo[]=bar
foo[]=baz
assoc[key1]=car
assoc[otherkey]=bus

foo[]="other value"
foo[]=five
assoc[ov]="other value"

注意:结果可以由parse_ini_file()解析。

查看类了解其他方法和选项。

\Jelix\IniFile\MultiIniModifier允许同时加载两个ini文件,其中第二个文件“覆盖”第一个文件的值。

\Jelix\IniFile\IniModifierArray允许同时加载多个文件,并管理它们的值,就像合并了文件一样。

\Jelix\IniFile\Util包含用于读取、写入和合并ini文件的基本方法。这些都是围绕parse_ini_file()的包装。