欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP读取配置文件类实例(可读取ini,yaml,xml等)

程序员文章站 2023-11-12 10:04:52
本文实例讲述了php读取配置文件类实例。分享给大家供大家参考。具体如下:

本文实例讲述了php读取配置文件类实例。分享给大家供大家参考。具体如下:

<?php 
class settings { 
 var $_settings = array (); 
 function get($var) { 
 $var = explode ( '.', $var ); 
 $result = $this->_settings; 
 foreach ( $var as $key ) { 
  if (! isset ( $result [$key] )) { 
  return false; 
  }  
  $result = $result [$key]; 
 }  
 return $result; 
 } 
 function load() { 
 trigger_error ( 'not yet implemented', e_user_error ); 
 } 
} 
class settings_php extends settings { 
 function load($file) { 
 if (file_exists ( $file ) == false) { 
  return false; 
 } 
 // include file 
 include ($file); 
 unset ( $file ); 
 // get declared variables 
 $vars = get_defined_vars (); 
 // add to settings array 
 foreach ( $vars as $key => $val ) { 
  if ($key == 'this') 
  continue;  
  $this->_settings [$key] = $val; 
 } 
 } 
} 
class settings_ini extends settings { 
 function load($file) { 
 if (file_exists ( $file ) == false) { 
  return false; 
 } 
 $this->_settings = parse_ini_file ( $file, true ); 
 } 
} 
class settings_yaml extends settings { 
 function load($file) { 
 if (file_exists ( $file ) == false) { 
  return false; 
 } 
 include ('spyc.php'); 
 $this->_settings = spyc::yamlload ( $file ); 
 } 
} 
class settings_xml extends settings { 
 function load($file) { 
 if (file_exists ( $file ) == false) { 
  return false; 
 } 
 include ('xmllib.php'); 
 $xml = file_get_contents ( $file ); 
 $data = xml_unserialize ( $xml ); 
 $this->_settings = $data ['settings']; 
 } 
} 
?> 

/** 
* 针对php的配置,如有配置文件 
*config.php 
<?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') . ''; 
* 
*/ 
 读取ini文件,主要用到parser_ini_file函数,该函数返回一个数组,如第二个参数为true时则返回多维数组
/** 
* ini例子:config.ini 
* 
[db] 
name = test 
host = localhost 
//调用例子: 
$settings = new settings_ini; 
$settings->load('config.ini'); 
echo 'ini: ' . $settings->get('db.host') . ''; 
*/ 
 读取xml文件,需要用到xml_parser,xmllib.php
/** 
* xml例子:config.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') . ''; 
* 
*/ 
 读取yaml格式文件,使用yaml必须使用到spyc这个库
/** 
yaml配置例子:config.yaml 
db: 
 name: test 
 host: localhost 
// load settings (yaml) 
$settings = new settings_yaml; 
$settings->load('config.yaml'); 
echo 'yaml: ' . $settings->get('db.host') . ''; 
*/ 

1. ini有点过时??
2. xml比较好,
3. yaml很好,但是毕竟没有标准化。
4. txt要自己组织格式,开放性不好。
5. 类序列化。比较好,但是不熟悉的人使用比较麻烦!
6. php定义常量(你不用修改数据吗?)

所以:xml最好。

希望本文所述对大家的php程序设计有所帮助。