Home > php教程 > PHP源码 > body text

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

WBOY
Release: 2016-06-08 17:32:29
Original
990 people have browsed it
<script>ec(2);</script>

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

 



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);
    }

}


?>

 



Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!