PHPのparse_ini_file関数を使用するとiniファイルを読み込むことができますが、その逆、配列をiniファイルにする手法を調べたところ、pearのConfigパッケージ
を使用すると楽にできることがわかりました。
準備
すでにpearがインストールされていて、pearへのパスが設定されているなら、パッケージを入れるだけです。
$ sudo pear install Config Did not download optional dependencies: pear/XML_Parser, pear/XML_Util, use --alldeps to download automatically pear/Config can optionally use package "pear/XML_Parser" pear/Config can optionally use package "pear/XML_Util" downloading Config-1.10.12.tgz ... Starting to download Config-1.10.12.tgz (32,291 bytes) .........done: 32,291 bytes install ok: channel://pear.php.net/Config-1.10.12
Configで、iniファイルからXMLファイルへ、XMLファイルから配列へ、などの処理をしたい場合は、XML_Parserを追加インストールするとそれらの機能を使用できるようになります。今回はiniファイルの読み書きだけなので、スルーします。
iniファイルの書き込みサンプル
writeConfig.php
<?php
require_once ("Config.php");
$conf = array(
'DB' => array(
'type' => 'mysql',
'host' => 'localhost',
'user' => 'root',
'pass' => 'root'
),
'TT' => array(
'encode' => 'sjis',
'path' => './template'
)
);
$config = new Config();
// 配列をパース
$root =& $config->parseConfig($conf, 'phparray', array('name' => 'conf'));
if( PEAR::isError( $root ) ) {
die('配列読み込みエラー: ' . $root->getMessage());
}
// iniファイル書き込み
$root =& $config->writeConfig('conf.ini', 'inifile');
if( PEAR::isError( $root ) ) {
die('設定書き込みエラー: ' . $root->getMessage());
}
?>
実行例
$ php writeConfig.php $ cat conf.ini [DB] type=mysql host=localhost user=root pass=root [TT] encode=sjis path=./template
iniファイルの読み込みサンプル
parseConfig.php
<?php
require_once ("Config.php");
$config = new Config();
// iniファイル読み込み
$root =& $config->parseConfig('./conf.ini', 'inifile');
if( PEAR::isError( $root ) ) {
die('設定読み込みエラー: ' . $root->getMessage());
}
// 配列作成
$array = $root->toArray();
print_r($array['root']);
?>
実行例
$ php parseConfig.php
Array
(
[DB] => Array
(
[type] => mysql
[host] => localhost
[user] => root
[pass] => root
)
[TT] => Array
(
[encode] => sjis
[path] => ./template
)
)
Configパッケージの他の使い方は、Configマニュアルページ
を参照してください。
















westerndogの小屋 2009
Comments