由于最近珊妹儿忙的不可开交,所以都没有时间写博客了,今天就给大家分享一个将数组写入文件的例子,此背景是在动态修改自定义的配置文件,而珊妹儿的配置文件格式是类似这种config.php:
<?php
$config=array(
'username'=>'wushanshan',
'frinds'=>array(
'boys'=>'none',
'girls'=>'more'
),
)
多维数组形式,首先我们来读取这个文件内容建立controller->test.php文件,建立models->test.class.php文件,
test.class.php内容如下:
<?php
class testModel {
protected static $data; //数组
protected static $file; //文件路径
/**
* 设置
* @param $data
* @param $path
*/
static function setConfig($data,$path) {
self::$data = $data;
self::$file = $path;
}
/**
* 获取数据
* @return mixed
*/
static function getConfig() {
return self::$data;
}
/**
* 修改配置文件
* @param $bns
* @return string
*/
static function writebns($bns){
$text="<?php\n\$config=".var_export($bns,true).';';//此处百度上有说使用print_r,但是珊妹儿试过,写入的数组关联索引没有引号,再次读取就会报错,所以换了这个就没问题了
if(false!==fopen(self::$file,'w+')){
$res = file_put_contents(self::$file,$text);
if($res){
return $res;
}else{
return '写入失败';
}
}else{
return '打开文件失败';
}
}
}
test.php内容如下:
require_once('test.class.php');//路径啊
require_once('config.php');//路径啊
testModel::setConfig($config,'config.php');//第一个是配置文件的变量,第二个是配置文件路径
unset($config);
class testController
{
/**
* 查询
* @param $arrReq
* @return mixed
*/
static public function index($arrReq){
$bns = testModel::getConfig();
$info['code'] = 0;
$info['msg'] = 'success!';
$info['data'] = $bns;
echo json_encode($info);
}
/**
* 修改/新增
* @param $arrReq
* @return mixed
*/
public function updatebns($arrReq){
$data = json_decode(urldecode($arrReq['module']),true); //此处省略n行逻辑代码,参数格式根据自己的场景处理
$res = testModel::writebns($data);
}}
珊妹儿自知自己写的代码可读性很差,所以只是给大家做个参考,如有好的建议,欢迎指点!!!!
X_X严谨吐槽,共创文明博客论坛
博主分享将数组写入文件的例子,背景是动态修改自定义配置文件,配置文件为多维数组形式的config.php。还介绍了建立controller->test.php和models->test.class.php文件,代码可读性仅供参考,欢迎提建议。

被折叠的 条评论
为什么被折叠?



