將數組有格式的寫入文件(包括讀取)

由於最近珊妹兒忙的不可開交,所以都沒有時間寫博客了,今天就給大家分享一個將數組寫入文件的例子,此背景是在動態修改自定義的配置文件,而珊妹兒的配置文件格式是類似這種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嚴謹吐槽,共創文明博客論壇

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章