Configuration.class.php
class Configuration
{
private $configFile;
private $items=array();
function Ini($configFile)
{
$this->configFile=$configFile;
$this->parse();
}
//获取属性
function __get($id)
{
return $this->items[$id];
}
//设置属性
function __set($key,$value)
{
$this->items[$key]=$value;
}
//解析XML文件保存到数组
function parse()
{
$doc=new DOMDocument();
$doc->load($this->configFile);
$cn=$doc->getElementsByTagName('config');
$nodes=$cn->item(0)->getElementsByTagName('*');
foreach($nodes as $node)
{
$this->items[$node->nodeName]=$node->nodeValue;
}
}
//保存XML文件
function save()
{
$doc=new DOMDocument();
$doc->formatOutput=true;
$r=$doc->createElement('config');
$doc->appendChild($r);
foreach($this->items as $k=>$v)
{
$keyName=$doc->createElement($k);
$keyName->appendChild($doc->createTextNode($v));
$r->appendChild($keyName);
}
copy($this->configFile,$this->configFile.".bak");
if($doc->save($this->configFile))
{
return true;
}
else
{
return false;
}
}
}
然后只要实例化上面的类,然后调用里面的INI方法就可以读取XML文件中的数据了
例:
var $config;
function config($parameter)
{
if(empty($this->config))
{
$this->config= new Configuration();
$this->config->Ini('config.xml');
}
return @$this->config->$parameter;
}
config.xml 里的内容为下
<?xml version="1.0"?>
<config>
<version>1.0</version>
<template_dir>views</template_dir>
<cache_dir>cache</cache_dir>
<db_host>localhost</db_host>
<db_user>root</db_user>
<db_password>123</db_password>
<db_database>jiaohui</db_database>
<db_table>jiaohui</db_table>
<site_root>http://192.168.1.5/</site_root>
<index_router>admin</index_router>
<site_name>test</site_name>
</config>
现在只要调用上面的config函数就可以得到XML中的相关数据
如:$this->config('site_root'); 就会得出http://192.168.1.5/。