将数组有格式的写入文件(包括读取)

由于最近珊妹儿忙的不可开交,所以都没有时间写博客了,今天就给大家分享一个将数组写入文件的例子,此背景是在动态修改自定义的配置文件,而珊妹儿的配置文件格式是类似这种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严谨吐槽,共创文明博客论坛

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值