1. 程式人生 > >php操作properties檔案的類,只讀

php操作properties檔案的類,只讀

class Config_File:

 <?php

/**
 * Config_File class.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @link http://smarty.php.net/
 * @version 2.6.15
 * @copyright Copyright: 2001-2005 New Digital Group, Inc.
 * @author Andrei Zmievski <
[email protected]
>
 * @access public
 * @package Smarty
 */

/* $Id: Config_File.class.php,v 1.85 2006/05/28 17:35:05 mohrt Exp $ */

/**
 * Config file reading class
 * @package Smarty
 */
class Config_File {
    /**#@+
     * Options
     * @var boolean
     */
    /**
     * Controls whether variables with the same name overwrite each other.
     */
    var $overwrite        =    true;

    /**
     * Controls whether config values of on/true/yes and off/false/no get
     * converted to boolean values automatically.
     */
    var $booleanize        =    true;

    /**
     * Controls whether hidden config sections/vars are read from the file.
     */
    var $read_hidden     =    true;

    /**
     * Controls whether or not to fix mac or dos formatted newlines.
     * If set to true, /r or /r/n will be changed to /n.
     */
    var $fix_newlines =    true;
    /**#@-*/

    /** @access private */
    var $_config_path    = "";
    var $_config_data    = array();
    /**#@-*/

    /**
     * Constructs a new config file class.
     *
     * @param string $config_path (optional) path to the config files
     */
    function Config_File($config_path = NULL)
    {
        if (isset($config_path))
            $this->set_path($config_path);
    }


    /**
     * Set the path where configuration files can be found.
     *
     * @param string $config_path path to the config files
     */
    function set_path($config_path)
    {
        if (!empty($config_path)) {
            if (!is_string($config_path) || !file_exists($config_path) || !is_dir($config_path)) {
                $this->_trigger_error_msg("Bad config file path '$config_path'");
                return;
            }
            if(substr($config_path, -1) != DIRECTORY_SEPARATOR) {
                $config_path .= DIRECTORY_SEPARATOR;
            }

            $this->_config_path = $config_path;
        }
    }


    /**
     * Retrieves config info based on the file, section, and variable name.
     *
     * @param string $file_name config file to get info for
     * @param string $section_name (optional) section to get info for
     * @param string $var_name (optional) variable to get info for
     * @return string|array a value or array of values
     */
    function get($file_name, $section_name = NULL, $var_name = NULL)
    {
        if (empty($file_name)) {
            $this->_trigger_error_msg('Empty config file name');
            return;
        } else {
            $file_name = $this->_config_path . $file_name;
            if (!isset($this->_config_data[$file_name]))
                $this->load_file($file_name, false);
        }

        if (!empty($var_name)) {
            if (empty($section_name)) {
                return $this->_config_data[$file_name]["vars"][$var_name];
            } else {
                if(isset($this->_config_data[$file_name]["sections"][$section_name]["vars"][$var_name]))
                    return $this->_config_data[$file_name]["sections"][$section_name]["vars"][$var_name];
                else
                    return array();
            }
        } else {
            if (empty($section_name)) {
                return (array)$this->_config_data[$file_name]["vars"];
            } else {
                if(isset($this->_config_data[$file_name]["sections"][$section_name]["vars"]))
                    return (array)$this->_config_data[$file_name]["sections"][$section_name]["vars"];
                else
                    return array();
            }
        }
    }


    /**
     * Retrieves config info based on the key.
     *
     * @param $file_name string config key (filename/section/var)
     * @return string|array same as get()
     * @uses get() retrieves information from config file and returns it
     */
    function &get_key($config_key)
    {
        list($file_name, $section_name, $var_name) = explode('/', $config_key, 3);
        $result = &$this->get($file_name, $section_name, $var_name);
        return $result;
    }

    /**
     * Get all loaded config file names.
     *
     * @return array an array of loaded config file names
     */
    function get_file_names()
    {
        return array_keys($this->_config_data);
    }


    /**
     * Get all section names from a loaded file.
     *
     * @param string $file_name config file to get section names from
     * @return array an array of section names from the specified file
     */
    function get_section_names($file_name)
    {
        $file_name = $this->_config_path . $file_name;
        if (!isset($this->_config_data[$file_name])) {
            $this->_trigger_error_msg("Unknown config file '$file_name'");
            return;
        }

        return array_keys($this->_config_data[$file_name]["sections"]);
    }


    /**
     * Get all global or section variable names.
     *
     * @param string $file_name config file to get info for
     * @param string $section_name (optional) section to get info for
     * @return array an array of variables names from the specified file/section
     */
    function get_var_names($file_name, $section = NULL)
    {
        if (empty($file_name)) {
            $this->_trigger_error_msg('Empty config file name');
            return;
        } else if (!isset($this->_config_data[$file_name])) {
            $this->_trigger_error_msg("Unknown config file '$file_name'");
            return;
        }

        if (empty($section))
            return array_keys($this->_config_data[$file_name]["vars"]);
        else
            return array_keys($this->_config_data[$file_name]["sections"][$section]["vars"]);
    }


    /**
     * Clear loaded config data for a certain file or all files.
     *
     * @param string $file_name file to clear config data for
     */
    function clear($file_name = NULL)
    {
        if ($file_name === NULL)
            $this->_config_data = array();
        else if (isset($this->_config_data[$file_name]))
            $this->_config_data[$file_name] = array();
    }


    /**
     * Load a configuration file manually.
     *
     * @param string $file_name file name to load
     * @param boolean $prepend_path whether current config path should be
     *                              prepended to the filename
     */
    function load_file($file_name, $prepend_path = true)
    {
        if ($prepend_path && $this->_config_path != "")
            $config_file = $this->_config_path . $file_name;
        else
            $config_file = $file_name;

        ini_set('track_errors', true);
        $fp = @fopen($config_file, "r");
        if (!is_resource($fp)) {
            $this->_trigger_error_msg("Could not open config file '$config_file'");
            return false;
        }

        $contents = ($size = filesize($config_file)) ? fread($fp, $size) : '';
        fclose($fp);

        $this->_config_data[$config_file] = $this->parse_contents($contents);
        return true;
    }

    /**
     * Store the contents of a file manually.
     *
     * @param string $config_file file name of the related contents
     * @param string $contents the file-contents to parse
     */
    function set_file_contents($config_file, $contents)
    {
        $this->_config_data[$config_file] = $this->parse_contents($contents);
        return true;
    }

    /**
     * parse the source of a configuration file manually.
     *
     * @param string $contents the file-contents to parse
     */
    function parse_contents($contents)
    {
        if($this->fix_newlines) {
            // fix mac/dos formatted newlines
            $contents = preg_replace('!/r/n?!', "/n", $contents);
        }

        $config_data = array();
        $config_data['sections'] = array();
        $config_data['vars'] = array();

        /* reference to fill with data */
        $vars =& $config_data['vars'];

        /* parse file line by line */
        preg_match_all('!^.*/r?/n?!m', $contents, $match);
        $lines = $match[0];
        for ($i=0, $count=count($lines); $i<$count; $i++) {
            $line = $lines[$i];
            if (empty($line)) continue;

            if ( substr($line, 0, 1) == '[' && preg_match('!^/[(.*?)/]!', $line, $match) ) {
                /* section found */
                if (substr($match[1], 0, 1) == '.') {
                    /* hidden section */
                    if ($this->read_hidden) {
                        $section_name = substr($match[1], 1);
                    } else {
                        /* break reference to $vars to ignore hidden section */
                        unset($vars);
                        $vars = array();
                        continue;
                    }
                } else {                    
                    $section_name = $match[1];
                }
                if (!isset($config_data['sections'][$section_name]))
                    $config_data['sections'][$section_name] = array('vars' => array());
                $vars =& $config_data['sections'][$section_name]['vars'];
                continue;
            }

            if (preg_match('/^/s*(/.?/w+)/s*=/s*(.*)/s', $line, $match)) {
                /* variable found */
                $var_name = rtrim($match[1]);
                if (strpos($match[2], '"""') === 0) {
                    /* handle multiline-value */
                    $lines[$i] = substr($match[2], 3);
                    $var_value = '';
                    while ($i<$count) {
                        if (($pos = strpos($lines[$i], '"""')) === false) {
                            $var_value .= $lines[$i++];
                        } else {
                            /* end of multiline-value */
                            $var_value .= substr($lines[$i], 0, $pos);
                            break;
                        }
                    }
                    $booleanize = false;

                } else {
                    /* handle simple value */
                    $var_value = preg_replace('/^([/'"])(.*)/1$/', '/2', rtrim($match[2]));
                    $booleanize = $this->booleanize;

                }
                $this->_set_config_var($vars, $var_name, $var_value, $booleanize);
            }
            /* else unparsable line / means it is a comment / means ignore it */
        }
        return $config_data;
    }

    /**#@+ @access private */
    /**
     * @param array &$container
     * @param string $var_name
     * @param mixed $var_value
     * @param boolean $booleanize determines whether $var_value is converted to
     *                            to true/false
     */
    function _set_config_var(&$container, $var_name, $var_value, $booleanize)
    {
        if (substr($var_name, 0, 1) == '.') {
            if (!$this->read_hidden)
                return;
            else
                $var_name = substr($var_name, 1);
        }

        if (!preg_match("/^[a-zA-Z_]/w*$/", $var_name)) {
            $this->_trigger_error_msg("Bad variable name '$var_name'");
            return;
        }

        if ($booleanize) {
            if (preg_match("/^(on|true|yes)$/i", $var_value))
                $var_value = true;
            else if (preg_match("/^(off|false|no)$/i", $var_value))
                $var_value = false;
        }

        if (!isset($container[$var_name]) || $this->overwrite)
            $container[$var_name] = $var_value;
        else {
            settype($container[$var_name], 'array');
            $container[$var_name][] = $var_value;
        }
    }

    /**
     * @uses trigger_error() creates a PHP warning/error
     * @param string $error_msg
     * @param integer $error_type one of
     */
    function _trigger_error_msg($error_msg, $error_type = E_USER_WARNING)
    {
        trigger_error("Config_File error: $error_msg", $error_type);
    }
    /**#@-*/
}

?>
class Config:

<?php

require_once ('lib/log4php/LoggerManager.php');
require_once ('lib/smarty/Config_File.class.php');

class Config {
 
  private $logger = null;
  private $config = null;
 
  private $fileName = null;
  private $path = null;
 
  public function __construct($configFileName, $directory=null){
    $this->fileName = $configFileName;
    $this->path = $directory;   
    $this->loadConfigFile();    
  }

  public  function loadConfigFile(){
    if($this->path == null){
      $this->config = new Config_File('./');
    }else{
      $this->config = new Config_File($this->path);
    }     
    $this->config->load_file($this->fileName, true);
  }
 
  public  function reloadConfigFile(){
    $this->loadConfigFile();
  }
 
  public  function addConfigItems($array, $sectionName=null){
  }

  public  function saveConfigFile(){
  }
 
  /**
   * get the value of specified key
   * @return: value
   */
  public  function getItem($key, $sectionName=null, $defaultValue=null){
    $result = null;
    $sections = $this->getSections();
    if($sections != null && count($sections) > 0){
     
      /* return the value for specified section*/
      if($sectionName != null){
    $result = $this->config->get($this->fileName, $sectionName, $key);
   
      }else{
    /* search all section for specified key
     * make sure no the same key for all sections
     * return the key's value found firstly
     */
    for($i = 0; $i < count($sections); $i++){   
      $value = $this->config->get($this->fileName, $sections[$i], $key);
      if($value != null)
        $result = $value;
    }
      }   
    }         
    if(!empty($result)) return $result;
   
    /* if config file has no section */
    $result = $this->config->get($this->fileName, $sectionName, $key);

    if(!empty($result)) return $result;
   
    return $defaultValue;
  }

  /**
   * get all items of config file
   * @return: ARRAY[KEY][VALUE]
   */
  public  function getAllItems(){
    $sections = $this->getSections();
    /* collect all sections' value*/
    if($sections != null && count($sections) > 0){     
      $value = array();
      for($i = 0; $i < count($sections); $i++){
    $value = array_merge($value, $this->config->get($this->fileName, $sections[$i]));
      }
      return $value;     
    }
    /* if no section, return all values in the file */
    $vars = $this->config->get($this->fileName);
    return $vars;
  }

  /**
   * get items of specified key in array
   * @param:   ARRAY[KEY]
   * @return:  ARRAY[KEY][VALUE]
   */
  public  function getItems($array){   
    $value = array();
    $items = $this->getAllItems();
    foreach($array as $key){
      $value[$key] = $items[$key];
    }
    return $value;
  }

  /**
   * get all items of specified section
   * @return: ARRAY[KEY][VALUE]
   */
  public function getSectionItems($sectionName){
    if($sectionName == null) return array();

    $sections = $this->getSections();
    if($sections != null && count($sections) > 0){
      return $this->config->get($this->fileName, $sectionName);
    }
    return array();
  }

  /**
   * get all items of specified section
   * @return: ARRAY[KEY][VALUE]
   */
  public function getNSectionItems($sectionName){
    if($sectionName == null) return array();

    $sections = $this->getSections();
    if($sections != null && count($sections) > 0){
      $result = $this->config->get($this->fileName, $sectionName);
      $res = array();
      foreach($result as $key=>$value){
        $res[substr($key, 1)]=$value;
      }
      return $res;
    }
    return array();
  }

 
  /**
   * get section names
   * @return: ARRAY
   */
  public function getSections(){
    return $this->config->get_section_names($this->fileName);
  }

  public function toString(){
    return $this->path . "/" . $this->fileName . "/n" ;
  }
}

?>

通過config類來操作properties檔案,

相關推薦

php操作properties檔案,只讀

class Config_File: <?php/** * Config_File class. * * This library is free software; you can redistribute it and/or * modify it under th

解決修改properties 屬性檔案存在快取問題,附帶操作properties檔案工具

     在做專案的時候有些資料不一定需要在資料庫管理,例如資料庫連線,定時任務等等的配置..有時候需要動態修改這些資料,但在修改完後,再次獲取時出現問題.    在專案中要修改properties,修改之後,再進入相關目錄檢視properties檔案,發現內容已經修改了,

php操作redis工具

config.php <?php // //redis配置 define('HOST','localhost'); define('PORT', '6379'); define('OVERTIME', '0'); ?> Redistool.php <?php inclu

C# 操作INI檔案

    //補充:        //using System;     //using System.Runtime.InteropServices;     //using System.Text;     //using System.Collections;    

PHP操作MySql封裝

mysqlconfig.php <?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PWD', '123456'); define('DB_CHARSET',

C#操作Ini檔案

      在Windows系統中,INI檔案是很多,最重要的就是“System.ini”、“System32.ini”和“Win.ini”。該檔案主要存放使用者所做的選擇以及系統的各種引數。使用者可以通過修改INI檔案,來改變應用程式和系統的很多配置。但自從Windows

JAVA操作properties檔案

1.方法一(放在src的路徑下) InputStream fis =TestProperties.class.getClassLoader().getResourceAsStream("init.properties") 2.方法二(要求TestProperties和in

java中操作properties檔案

 private String loadSysPath(){  String temp = "./cluster/siteId/conf/netMap.properties";  if(temp.indexOf("siteId")!=-1){   String siteId=

PHP操作RabbitMQ的 exchange、queue、route kye、bind

null class 應用 取數 span date 特殊 json 功能 RabbitMQ是常見的消息中間件。也許是還是不夠了解的緣故,感覺功能還好吧。 講到隊列,大家腦子裏第一印象是下邊這樣的。 P生產者推送消息-->隊列-->C消費者取出消息 結構很

Properties檔案工具的使用--獲取所有的鍵值、刪除鍵、更新鍵等操作

  有時候我們希望處理properties檔案,properties檔案是鍵值對的檔案形式,我們可以藉助Properties類操作。  工具類如下:(程式碼中日誌採用了slf4j日誌) package cn.xm.exam.utils; import java.io.File; i

php使用phpexcel操作excel檔案資料

php使用phpexcel類操作excel檔案資料 首先下載phpexcel git地址:https://github.com/PHPOffice/PHPExcel/releases 這裡下載了1.8.1.zip 解壓之後進入目錄,Classes目錄,複製PHPExcel.php和

PHP的ftp檔案,多檔案上傳操作

PHP針對ftp檔案的操作方法,如果是隻操作一個ftp,可以使用裡面的單利模式, 不需要每次都去例項化,我的專案中需要去連結很多個ftp伺服器; 所以需要多次去連線和關閉; 1 2 3 4 5 6 7

PHP學習】檔案程式設計——對目錄的操作

什麼是檔案程式設計 所謂的檔案程式設計技術,指的就是對==檔案==或==目錄==的==增刪改查操作 可參考菜鳥教程:http://www.runoob.com/php/php-ref-filesystem.html 檔案程式設計的分類 對目錄的操作 對檔案的操作 對目錄的操作

讀取.properties檔案的工具

package com.javaTest; import java.io.File; import java.io.IOException; import java.util.Properties; import org.springframework.core.io.FileSystemR

PHP匯出word檔案,簡單拓展可匯出其他文字檔案

PHP匯出word檔案,簡單拓展可匯出其他文字類檔案 /** * PHP 匯出簡單文字內容(word txt等) * @param $content mixed 匯出內容 (文字string / html程式碼) * @param $filename string 需儲存檔名 * @

PHP設計模式:自動載入、PSR-0規範、鏈式操作、11種面向物件設計模式實現和使用、OOP的基本原則和自動載入配置

一、類自動載入      SPL函式 (standard php librarys)      類自動載入,儘管 __autoload() 函式也能自動載入類和介面,但更建議使用&nbs

Properties 配置檔案

介紹 Properties(配置檔案類):主要用於生成配置檔案與讀取配置檔案的資訊。屬於集合體系的類,繼承了Hashtable類,實現了Map介面 因為 Properties 繼承於 Hashtable,所以可對 Properties 物件應用 put 和 putAll 方法。但

PHP 檔案操作檔案讀取

檔案讀取 fread 函式 引數$fd,$file_size; 獲取檔案的大小 filesize($path); 引數$path 檔案路徑; 字串替換 str_replace("\r\n","<br>",$con_str); <?php header("cont

java 讀取properties檔案通用工具

1.建立 PropertiesUtil.java檔案: package com.demo.util; import java.util.ResourceBundle; /** * 對系統中的config.properties配置檔案內容讀取工具類 * * Created by zha

Java工具--讀取Properties檔案

package com.skr.mdm.util; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import java.io.InputStreamReader; import java.util.*; /** *