PHP获取XML配置文件

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值