Home  >  Article  >  Backend Development  >  php怎么修改配置文件

php怎么修改配置文件

WBOY
WBOYOriginal
2016-06-13 12:50:14904browse

php如何修改配置文件
Config.php代码如下:

 <?php<br />
<br />
return array(<br />
        'version' => '20120823',<br />
	'secretKey' => '92fe5927095eaac53cd1aa3408da8135',<br />
	'areaname' => 'China',<br />
);<br />


现在想写个Common.php定义setConfig($fileName, $value)方法,去修改areaname的值。其中$fileName为Config.php文件名称, $value为更换的值,不知道具体怎么写??

php 配置文件 数组
------解决方案--------------------
file_get_contents()
file_put_contents()
------解决方案--------------------
function setConfig($fileName, $value) {<br />
  ob_start();<br />
  $a = @include($fileName);<br />
  ob_end_clean();<br />
  if(! is_array($a)) trigger_error("Invalid data file", E_USER_ERROR);<br />
  $a['areaname'] = $value;<br />
  file_put_contents($fileName, '<?php return ' . var_export($a, 1) . ';');<br />
}<br />
<br />
setConfig('config.php', 'aaa');

但是由于你的方案的限制,这个函数有着不通用的毛病
比如要想修改 secretKey 就不可以了
建议改写做
function setConfig($key, $value, $fileName='config.php') {<br />
  ob_start();<br />
  $a = @include($fileName);<br />
  ob_end_clean();<br />
  if(! is_array($a)) trigger_error("Invalid data file", E_USER_ERROR);<br />
  $a[$key] = $value;<br />
  file_put_contents($fileName, '<?php return ' . var_export($a, 1) . ';');<br />
}<br />
<br />
setConfig('areaname', 'bbb');

------解决方案--------------------
楼上正解,好的开发者一定在通用性上有想法
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn