php运维开发需要,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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值