在PHP中存储可轻松编辑的配置数据的最快方法? [英] Fastest way to store easily editable config data in PHP?

查看:78
本文介绍了在PHP中存储可轻松编辑的配置数据的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中存储配置数据以使其易于更改(通过PHP)的最快方法是什么?首先,我考虑过使用config.php文件,但是我不能用PHP即时编辑它,至少不是很简单吗?然后,我想到了具有XML文件的功能,但是为每个HTTP请求解析它们的工作量很大.因此,我考虑了INI文件,但随后我发现INI文件仅限于int/string值.最后,我得出的结论是JSON编码的文件是最好的:

What is the fastest way to store config data in PHP so that it is easily changeable (via PHP)? First I thought about having config.php file, but I can't edit it on fly with PHP, at least not very simply? Then I thought about having XML files, but parsing them for each HTTP request is overwhelming. So, I thought about INI files, but then I figured that INI files are restricted to int/string values. In the end, I have come to the conclusion that JSON encoded file is the best:

$config['database']['host'] = ...;
$config['another']['something'] = ...;
...
json_encode($config);

由于JSON可以存储数组,因此我可以使用它创建非常复杂的配置,并且解析速度比INI文件快.

Since JSON can store arrays, I can create quite complex configurations with it, and it parses faster than INI files.

我的问题:我错过了什么吗?或者有更好的方法吗?

My question: did I miss something or is there a better way to do this?

推荐答案

对于存储PHP变量,序列化是比JSON更好的选择.

Serialize is a better option than JSON for storing PHP variables.

我喜欢使用var_export保存配置文件,并使用include加载配置信息.这样可以很容易地以编程方式保存配置数据,也可以使人也易于读取/写入数据:

I like to use var_export for saving config file, and using include for loading config info. This makes it easy to save config data progmatically AND makes the data easy to read/write for a person as well:

config.php:

config.php:

return array(
 'var1'=> 'value1',
 'var2'=> 'value2',
);

test.php:

$config = include 'config.php';
$config['var2']= 'value3';
file_put_contents('config.php', '<?php return ' . var_export($config, true) . ';');

更新后的config.php现在包含以下内容:

Updated config.php now contains the following:

return array(
 'var1'=> 'value1',
 'var2'=> 'value3',
);

这篇关于在PHP中存储可轻松编辑的配置数据的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆