Php 如何将ini文件解析为对象

Php 如何将ini文件解析为对象,php,ini,Php,Ini,我正在获取ini文件的内容,如下所示 $file = 'config.ini'; if (!file_exists($file)) { $file = 'config.sample.ini'; } $config = parse_ini_file($file, true); 这将产生一个多维数组,但我更希望它是一个对象。parse_ini_file()是否可以实现这一点?我将如何实现这一点?如果要将数组转换为stdClass,请使用以下命令: $configObj = (object)

我正在获取ini文件的内容,如下所示

$file = 'config.ini';
if (!file_exists($file)) {
    $file = 'config.sample.ini';
}
$config = parse_ini_file($file, true);

这将产生一个多维数组,但我更希望它是一个对象。parse_ini_file()是否可以实现这一点?我将如何实现这一点?

如果要将数组转换为stdClass,请使用以下命令:

$configObj = (object) parse_ini_file($file, true);

您可以使用
json\u encode()
json\u decode()
来实现这一点:

$file = 'config.ini';
if (!file_exists($file)) {
  $file = 'config.sample.ini';
}
$config = parse_ini_file($file, true);
// convert to data to a json string
$config = json_encode($config);
// convert back from json, the second parameter is by
// default false, which will return an object rather than an
// associative array
$config = json_decode($config);
  • 可以使用两种方法将数组更改为object
  • 范例
  • 输出

如果您需要一些高级机制,请尝试以下代码示例

INI文件

[database]
databse.engine = mysqli
databse.host = localhost
databse.user = root
databse.password = demopass
databse.database = demodb
[cache]
enable_cache = false


class Config implements Countable, Iterator {
    protected $_data;
    protected $_count;
    protected $_index;
    public
    function __construct($config = array()) {
        if (sizeof($config) > 0) {
            foreach($config as $key = > $value) {
                if (is_array($value)) {
                    $this - > _data[$key] = new self($value);
                } else {
                    $this - > _data[$key] = $value;
                }
            }
        }
        $this - > _count = count($this - > _data);
    }
    public
    function get($name) {
        return array_key_exists($name, $this - > _data) ? $this - > _data[$name] : null;
    }
    public
    function __get($name) {
        return $this - > get($name);
    }
    public
    function __set($name, $value) {
        if (is_array($value)) {
            $this - > _data[$name] = new self($value);
        } else {
            $this - > _data[$name] = $value;
        }
        $this - > _count = count($this - > _data);
    }
    public
    function __clone() {
        $array = array();
        foreach($this - > _data as $key = > $value) {
            if ($value instanceof Config) {
                $array[$key] = clone $value;
            } else {
                $array[$key] = $value;
            }
        }
        $this - > _data = $array;
    }
    public
    function toArray() {
        $array = array();
        $data = $this - > _data;
        foreach($data as $key = > $value) {
            if ($value instanceof Config) {
                $array[$key] = $value - > toArray();
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }
    public
    function __isset($name) {
        return isset($this - > _data[$name]);
    }
    public
    function __unset($name) {
        unset($this - > _data[$name]);
        $this - > _count = count($this - > _data);
    }
    public
    function count() {
        return $this - > _count;
    }

    function rewind() {
        reset($this - > _data);
        $this - > _index = 0;
    }

    function current() {
        return current($this - > _data);
    }

    function key() {
        return key($this - > _data);
    }

    function next() {
        next($this - > _data);
        $this - > _index++;
    }

    function valid() {
        return $this - > _index < $this - > _count;
    }
}
class parseINI extends Config {
    protected $_filePath;
    public
    function __construct($iniPath = null) {
        try {
            if (!is_null($iniPath)) {
                $this - > _filePath = $iniFile;
            }
            $this - > __validateIniFile();
            $parse = parse_ini_file($this - > _filePath, true);
            parent::__construct($parse);
        } catch (ErrorException $ex) {
            print $ex - > getMessage();
        }
    }
    protected
    function __validateIniFile() {
        if (is_null($this - > _filePath)) {
            throw new ErrorException('Please set the path of ini file.');
        }
        elseif(!strtolower(pathinfo($this - > _filePath, PATHINFO_EXTENSION)) === 'ini') {
            throw new ErrorException('Provided file is not a valid ini file.');
        }
        elseif(!is_readable($this - > _filePath)) {
            throw new ErrorException('Provided file location is not a valid.');
        }
    }
    public
    function getConfig() {
        return new Config($this - > _data);
    }
}
echo '<pre>';
$parse = new parseINI('data/php.ini');
print_r($parse - > getConfig());
print_r($parse - > getConfig() - > get('database'));
[数据库]
database.engine=mysqli
database.host=localhost
database.user=root
database.password=demopass
database.database=demodab
[缓存]
启用\u缓存=false
类配置实现可数迭代器{
受保护的$u数据;
受保护的美元计数;
受保护的美元指数;
公众的
函数构造($config=array()){
如果(sizeof($config)>0){
foreach($config as$key=>$value){
if(是_数组($value)){
$this->_data[$key]=新的自我($value);
}否则{
$this->_数据[$key]=$value;
}
}
}
$this->\u count=count($this->\u数据);
}
公众的
函数get($name){
返回数组\u key\u是否存在($name,$this->\u data)?$this->\u data[$name]:null;
}
公众的
函数获取($name){
返回$this->get($name);
}
公众的
函数集($name,$value){
if(是_数组($value)){
$this->_data[$name]=新自我($value);
}否则{
$this->_数据[$name]=$value;
}
$this->\u count=count($this->\u数据);
}
公众的
函数_uclone(){
$array=array();
foreach($key=>$value形式的数据){
如果($value instanceof Config){
$array[$key]=克隆$value;
}否则{
$array[$key]=$value;
}
}
$this->_data=$array;
}
公众的
函数toArray(){
$array=array();
$data=$this->\u数据;
foreach($key=>$value形式的数据){
如果($value instanceof Config){
$array[$key]=$value->toArray();
}否则{
$array[$key]=$value;
}
}
返回$array;
}
公众的
函数集($name){
返回isset($this->_data[$name]);
}
公众的
函数未设置($name){
未设置($this->_data[$name]);
$this->\u count=count($this->\u数据);
}
公众的
函数计数(){
返回$this->\u计数;
}
函数倒带(){
重置($this->\u数据);
$this->_索引=0;
}
函数电流(){
返回当前数据($this->\u数据);
}
函数键(){
返回键($this->\u数据);
}
函数next(){
接下来($this->\u数据);
$this->_index++;
}
函数valid(){
返回$this->\u索引<$this->\u计数;
}
}
类parseINI扩展了Config{
受保护的$\u文件路径;
公众的
函数构造($iniPath=null){
试一试{
如果(!为null($iniPath)){
$this->_filePath=$iniFile;
}
$this->uu validateIniFile();
$parse=parse_ini_文件($this->_filePath,true);
父项::_构造($parse);
}捕获(错误异常$ex){
打印$ex->getMessage();
}
}
受保护的
函数uu validateIniFile(){
如果(为空($this->\u filePath)){
抛出新的ErrorException('请设置ini文件的路径');
}
elseif(!strtolower(路径信息($this->\u文件路径,路径信息扩展))=='ini'){
抛出新的ErrorException('提供的文件不是有效的ini文件');
}
elseif(!可读($this->\u filePath)){
抛出新的ErrorException('提供的文件位置无效');
}
}
公众的
函数getConfig(){
返回新配置($this->\u数据);
}
}
回声';
$parse=newparseini('data/php.ini');
打印($parse->getConfig());
打印($parse->getConfig()->get('database');

你可以选择:和(谷歌的前两个结果:
php parse_ini_file to object
)@jakojack你看到我的评论了吗@里齐尔:的确是这样。谢谢。只是一个小小的补充(如果与您相关,则不知道):要编码/解码的字符串必须是UTF-8,否则您可能会在过程中遇到问题。


    $configArr = array(
        'NAME' => 'stack over flow',
        'AGE'  => 28,
        'SEX'  => 'MALE',
    );
    $configObj = arrayToObject($configArr);
    var_dump($configObj);



    class stdClass#1 (3) {
      public $NAME => string(15) "stack over flow"
      public $AGE  => int(28)
      public $SEX  => string(4) "MALE"
    }

[database]
databse.engine = mysqli
databse.host = localhost
databse.user = root
databse.password = demopass
databse.database = demodb
[cache]
enable_cache = false


class Config implements Countable, Iterator {
    protected $_data;
    protected $_count;
    protected $_index;
    public
    function __construct($config = array()) {
        if (sizeof($config) > 0) {
            foreach($config as $key = > $value) {
                if (is_array($value)) {
                    $this - > _data[$key] = new self($value);
                } else {
                    $this - > _data[$key] = $value;
                }
            }
        }
        $this - > _count = count($this - > _data);
    }
    public
    function get($name) {
        return array_key_exists($name, $this - > _data) ? $this - > _data[$name] : null;
    }
    public
    function __get($name) {
        return $this - > get($name);
    }
    public
    function __set($name, $value) {
        if (is_array($value)) {
            $this - > _data[$name] = new self($value);
        } else {
            $this - > _data[$name] = $value;
        }
        $this - > _count = count($this - > _data);
    }
    public
    function __clone() {
        $array = array();
        foreach($this - > _data as $key = > $value) {
            if ($value instanceof Config) {
                $array[$key] = clone $value;
            } else {
                $array[$key] = $value;
            }
        }
        $this - > _data = $array;
    }
    public
    function toArray() {
        $array = array();
        $data = $this - > _data;
        foreach($data as $key = > $value) {
            if ($value instanceof Config) {
                $array[$key] = $value - > toArray();
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }
    public
    function __isset($name) {
        return isset($this - > _data[$name]);
    }
    public
    function __unset($name) {
        unset($this - > _data[$name]);
        $this - > _count = count($this - > _data);
    }
    public
    function count() {
        return $this - > _count;
    }

    function rewind() {
        reset($this - > _data);
        $this - > _index = 0;
    }

    function current() {
        return current($this - > _data);
    }

    function key() {
        return key($this - > _data);
    }

    function next() {
        next($this - > _data);
        $this - > _index++;
    }

    function valid() {
        return $this - > _index < $this - > _count;
    }
}
class parseINI extends Config {
    protected $_filePath;
    public
    function __construct($iniPath = null) {
        try {
            if (!is_null($iniPath)) {
                $this - > _filePath = $iniFile;
            }
            $this - > __validateIniFile();
            $parse = parse_ini_file($this - > _filePath, true);
            parent::__construct($parse);
        } catch (ErrorException $ex) {
            print $ex - > getMessage();
        }
    }
    protected
    function __validateIniFile() {
        if (is_null($this - > _filePath)) {
            throw new ErrorException('Please set the path of ini file.');
        }
        elseif(!strtolower(pathinfo($this - > _filePath, PATHINFO_EXTENSION)) === 'ini') {
            throw new ErrorException('Provided file is not a valid ini file.');
        }
        elseif(!is_readable($this - > _filePath)) {
            throw new ErrorException('Provided file location is not a valid.');
        }
    }
    public
    function getConfig() {
        return new Config($this - > _data);
    }
}
echo '<pre>';
$parse = new parseINI('data/php.ini');
print_r($parse - > getConfig());
print_r($parse - > getConfig() - > get('database'));