php讀取四種配置文件
分類: PHP開發(1)
<?php
/**
* 讀取4中配置的表信息,現支持php.ini,xml.yaml
*/
class Settings{
var $_settings = array();
/**
* 獲取某些設置的值
*
* @param unknown_type $var
* @return unknown
*/
function get($var) {
$var = explode('.', $var);
$result = $this->_settings;
foreach ($var as $key) {
if (!isset($result[$key])) { return false; }
$result = $result[$key];
}
return $result;
// trigger_error ('Not yet implemented', E_USER_ERROR);//引發一個錯誤
}
function load() {
trigger_error ('Not yet implemented', E_USER_ERROR);
}
}
/**
* 針對PHP的配置,如有配置文件
* $file=
<?php
$db = array();
// Enter your database name here:
$db['name'] = 'test';
// Enter the hostname of your MySQL server:
$db['host'] = 'localhost';
?>
具體調用:
include ('settings.php'); //原始環境假設每個類為單獨的一個類名.php文件
// Load settings (PHP)
$settings = new Settings_PHP;
$settings->load('config.php');
echo 'PHP: ' . $settings->get('db.host') . '';
*
*/
Class Settings_PHP Extends Settings {
function load ($file) {
if (file_exists($file) == false) { return false; }
// Include file
include ($file);
unset($file); //銷毀指定變量
$vars = get_defined_vars(); //返回所有已定義變量的列表,數組,變量包括服務器等相關變量,
//通過foreach吧$file引入的變量給添加到$_settings這個成員數組中去.
foreach ($vars as $key => $val) {
if ($key == 'this') continue;
$this->_settings[$key] = $val;
}
}
}
//////////////////////讀取INI文件,主要用到parser_ini_file函數,該函數返回一個數組,如第二個參數為true時則返回多維數組/////////////////////////////////////////
/**
* ini例子:
* [db]
name = test
host = localhost
調用例子:
$settings = new Settings_INI;
$settings->load('config.ini');
echo 'INI: ' . $settings->get('db.host') . '';
*
*/
Class Settings_INI Extends Settings {
function load ($file) {
if (file_exists($file) == false) { return false; }
$this->_settings = parse_ini_file ($file, true);
}
}
//////////////////////讀取XML文件,需要用到XML_PARSER//////////////////////////////////////////////////////////
/**
* XML例子:
<?xml version="1.0" encoding="UTF-8"?>
<settings>
<db>
<name>test</name>
<host>localhost</host>
</db>
</settings>
調用例子:
// Load settings (XML)
$settings = New Settings_XML;
$settings->load('config.xml');
echo 'XML: ' . $settings->get('db.host') . '';
*
*/
Class Settings_XML Extends Settings {
function load ($file) {
if (file_exists($file) == false) { return false; }
/**xmllib.php為PHP XML Library, version 1.2b,相關連接:http://keithdevens.com/software/phpxml
xmllib.php主要特點是把一個數組轉換成一個xml或吧xml轉換成一個數組
XML_unserialize:把一個xml給轉換 成一個數組
XML_serialize:把一個數組轉換成一個xml
自PHP5起,simpleXML就很不錯,但還是不支持將xml轉換成數組的功能,所以xmlLIB還是很不錯的.
*/
include ('xmllib.php');
$xml = file_get_contents($file);
$data = XML_unserialize($xml);
$this->_settings = $data['settings'];
}
}
//////////////////////////////////讀取YAML格式文件///////////////////////////////////////////////
/**
使用YAML必須使用到SPYC這個庫,相關鏈接在http://spyc.sourceforge.net/
YAML配置例子:
db:
name: test
host: localhost
*/
Class Settings_YAML Extends Settings {
function load ($file) {
if (file_exists($file) == false) { return false; }
include ('spyc.php');
$this->_settings = Spyc::YAMLLoad($file);
}
}