What's Is the Best File Format for Configuration Files

怎甘沉沦 提交于 2019-11-28 05:04:55

How about an INI file format? It's a de facto configuration file standard, and PHP has a built-in parser for that format:

parse_ini_file

YAML is a good option: http://www.yaml.org/

It's very simple and powerful, too

Ruby projects use it a lot for configuration.

Tiago

Why don´t you use a PHP file for the configuration?

The benefits are clear:

  • possible errors will get caught automatically
  • no need to use/create a custom parser
  • it´s widely understood by PHP programmers
  • you can have some custom logic, for example using custom configurations for development, others for production, etc

Other frameworks like Django and rails use a config file which is a script.

Another option would be to use JSON and use json_encode and json_decode.

You would be able to use richer data structures in your configuration parameters.

UnkwnTech

Personly I like to do config data in a class.

class appNameConfig {
    var $dbHost = 'localhost';
    var $dbUser = 'root';
    //...
 }

then to use them all you have to do is

$config = new appNameConfig;
mysql_connect($config->dbHost, $config->dbUser, $config->dbPassword) or die(/*...*/);

to change the config all you have to do is read the file with the class in it I use a function like this:

function updateConfig($parameter, $value) {
    $fh = fopen('config.php', 'w+');
    while(!feof($fh)) {
        $file .= fgets($fh);
     }
    $fileLines = explode("\n", $file);
    for($i=0;$i<count($fileLines);$i++) {
        if(strstr($fileLines[$i], $parameter)) {
            $fileLines[$i] = "$" . $parameter . " = '" . $value . "'";
         }
     }
    $file = implode("\n", $fileLines);
    fwrite($fh, $file);
    fclose($fh);
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!