最近在写运维开发时,经常碰见一些常见的文件的文件操作。
特别在处理高并发的需求时,需要REDIS DOCUMENT DB同时操作,如果业务人员在文件处理上花费太多的时间会降低开发效率,因此笔者把自己在开发中经常用的几个函数贴出来,提供给大家复制粘贴。如果代码上有什么问题,也希望大家提出来。

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');
}

调用时只需要把文件包含进来就可以


liaoyizhe
434 声望24 粉丝

语言不再强势,路的尽头是汇编