lkeme / inifile
类,用于读取和修改 ini 文件,同时保留注释和空行
该软件包的官方仓库似乎已不存在,因此该软件包已被冻结。
v3.4.0
2021-05-13 10:44 UTC
Requires
- php: >=7.0.0
Requires (Dev)
- phpunit/phpunit: 4.8.*
README
一些类,用于读取和修改 ini 文件,同时保留注释和空行。
它们支持章节和数组值。您还可以合并章节,合并两个 ini 文件,以及重命名一些值或章节。
安装
您可以通过 Composer 安装它。在您的项目中
composer require "jelix/inifile"
用法
\Jelix\IniFile\IniModifier 类允许读取 ini 文件,修改其内容(包括注释),并保存它,同时保留空行。
不要使用此类仅读取内容。相反,使用 \Jelix\IniFile\Util 或 parse_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() 的封装。