类来操作php中的.ini文件


Class to manipulate .ini files in php

我一直在玩我在网上发现的一个php类,叫做Config Magik,我用来在INI文件中存储一些信息,但最近在使用removeKey时遇到了一些问题。我想知道是否有人能给我介绍一个类似的课程,效果会一样好,甚至更好。或者是否有更好的方法来解决这个问题。

这是我现在的函数,在疯狂地摆弄它之后,所以它可能有很大的缺陷。

require_once('class.ConfigMagik.php');
$config = new ConfigMagik('config.ini', true, true);
if(!empty($_GET)){
    if(!is_writeable('config.ini')){
        echo 'Could not write to config.ini';
        return false;
    }
  //if there is no section parameter, we will not do anything.
  if(!isset($_GET['section'])){ 
    echo false; return false;
  } else {
    $section_name = $_GET['section'];
    unset($_GET['section']);     //Unset section so that we can use the GET variable to manipulate the other parameters in a foreach loop.
    if (!empty($_GET)){
      foreach ($_GET as $var => $value){
            echo $var.'='.$_GET[$var].'<br />';
            //Check if said variable $var exists in the section.
        if($config->get($var, $section_name) !== NULL){
            //Set variable value.
          try{
              $config->set($var, $value, $section_name);
              echo 'Setting variable '. $var.' to '.$value.' on section '.$section_name;
          } catch(Exception $e) {
                echo 'Could not set variable '.$var;
                echo $e;
                return false;
          }
        } else {
            echo $var.' does not exist <br />';
        }
      }
    }
    try{
      $section = $config->get($section_name); //Get the entire section so that we can manipulate it.
      echo '<pre>';print_r($section);echo '</pre>';
            foreach ($section as $title=>$value){
        if(!isset($_GET[$title]) && isset($section[$title])){
            try{
            $config->removeKey($title, $section_name);
            echo '<b>'.$title.'</b>: removed <br />';
            } catch(Exception $e){
                echo $e;
          }
        }
      }
    } catch(Exception $e){
        echo $e;
    }
    $config->save();
    //echo $config->toString('HTML');
    echo true;
    return true;
  }
} else { RUN SOME HTML }

它基本上保存了我从GET参数传递的设置,如果参数不存在,它应该删除它。当我得到$config->removeKey($title, $section_name);在最后的try catch语句中,它不会自动保存(因为它应该),所以我尝试运行$config->save(),我最终得到了一个到处都有section = array的ini文件。在过去的几周里,我一直在网上学习PHP,所以我相信我还有很长的路要走。

我已经明确地将问题隔离到$config->save()部分,只是不知道如何解决它。

我过去一直在使用Zend_Config_Ini和Zend_Config_Writer_Ini,并对其功能感到满意。你需要从Zend Framework中提取整个库/Zend/Config文件夹,并使Zend_Exception可用。