PHP運維開發常見文件操做

最近在寫運維開發時,常常遇見一些常見的文件的文件操做。
特別在處理高併發的需求時,須要REDIS DOCUMENT DB同時操做,若是業務人員在文件處理上花費太多的時間會下降開發效率,所以筆者把本身在開發中常常用的幾個函數貼出來,提供給你們複製粘貼。若是代碼上有什麼問題,也但願你們提出來。php

1.將字符串寫入文件中

w : Open for reading and writing; place the file pointer at the beginning of the file truncate the file to zero length.
a : Open for reading and writing; place the file pointer at the end of the file.數據庫

function inputStrToFile($filename, $writetext, $openmod = 'w'){
    $fp = fopen($filename, $openmod);
    if ($fp) {
        flock($fp, 2);
        fwrite($fp, $writetext);
        fclose($fp);
        return true;
    } else {
        return false;
    }
}

2.讀取文件字符串

function getFileToStr($fileName)
{
    $buffer = '';
    if (!file_exists($fileName)) {
        throw new Exception('文件不存在', 0);
    }
    $handle = fopen("./star_star_academy_set_10.txt", "r");
    while (!feof($handle)) {
        $buffer = $buffer . fgets($handle);
    }
    fclose($handle);
    return $buffer;
}

3.把JSON文件轉爲數組

function getJsonFileToArr($fileName)
{
    if (!file_exists($fileName)) {
        throw new Exception('文件不存在', 0);
    }
    //Open for reading only; place the file pointer at the beginning of the file
    $file = fopen($fileName, 'r');
    $filestr = fread($file, filesize($fileName));
    fclose($file);
    return json_decode($filestr, 'true');
}

4.從數據庫讀取數據存入JSON文件

function getDbToJsonFile($tableName, $fileName)
{
    //數據庫操做
    $data = $this->db->select($tableName, '*');
    $filestr = json_encode($data);
    //Open for reading and writing; place the file pointer at the beginning of the file
    //truncate the file to zero length.
    $file = fopen($this->filePath . $fileName, 'w');
    fwrite($file, $filestr);
    fclose($file);
}

5.將數組寫入文件

function inputArrToFile($filename, $array, $valueName)
{
    $cachefile = $filename;
    $cachetext = "<?php\r\n" . '$' . $valueName . '=' . var_export($array, true) . ';';
    return inputStrToFile($cachefile, $cachetext, 'w');
}

調用時只須要把文件包含進來就能夠json

相關文章
相關標籤/搜索