Home  >  Article  >  php教程  >  php 站点使用XML文件做配置类

php 站点使用XML文件做配置类

WBOY
WBOYOriginal
2016-06-08 17:32:29932browse

要用到,在网站上找了一个,然后自己整理成一个类..

 



php
/*
*PHP获取和设置XML节点,用于修改和读取站点配置文件
*2008-4-3 
*LIQUAN
*eg.get config 
*$c = new Configuration(''config.xml'');
*echo( $c->TemplateDirectory." " );
*
* set config
* $c = new Configuration(''config.xml'');
* $c->TemplateDirectory=''test'';
* $c->save();
*/

class Configuration
{
 
private $configFile;
 
private $items=array();
 
 
//构造函数
 function __construct($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");
    
    
$doc->save($this->configFile);
    }

}


?>

 



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn