问题
I am creating a framework in PHP and need to have a few configuration files. Some of these files will unavoidably have a large number of entries.
What format would be the best for these config files?
Here is my quantification of best:
- Easily parsed by PHP. It would be nice if I didn't have to write any parsing code but this is not a deal breaker.
- Remains easily read by humans even when there are a large amount of entries
- Is a widely used standard, no custom formats
- Succinctness is appreciated
I started out using XML, but quickly gave up for obvious reasons. I've thought of JSON and YAML but wanted to see what else is out there.
回答1:
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
回答2:
YAML is a good option: http://www.yaml.org/
It's very simple and powerful, too
Ruby projects use it a lot for configuration.
回答3:
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.
回答4:
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.
回答5:
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);
}
来源:https://stackoverflow.com/questions/476892/whats-is-the-best-file-format-for-configuration-files