- A+
所属分类:PHP
读取函数
- //文件读写函数
- function read_file(string $filename){
- //检测文件是否存在,且有读的权限
- if (is_file($filename) && is_readable($filename)){
- return file_get_contents($filename);
- }
- return false;
- }
- echo read_file('test_read.txt');
- //读取文件中的内容到数组中
- function read_file_array(string $filename,bool $skip_empty_lines=false){
- //判断文件是否存在,且有读的权限
- if (is_file($filename) && is_readable($filename)){
- if ($skip_empty_lines){
- return file($filename,FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
- }else{
- return file($filename);
- }
- }
- return false;
- }
- print_r(read_file_array('test_read.txt'));
写入函数
- //向文件中写入内容,且判断是否需要清空文件中的内容
- function write_file(string $filename,$data,$clearFlag=false){
- //dirname — 返回路径中的目录部分
- $dirname =dirname($filename);
- //检测目标路径是否存在
- if (!file_exists($dirname)){
- mkdir($dirname,'0777',true);
- }
- //检测文件是否存在并且可读
- if(is_file($filename) && is_readable($filename)){
- //通过判断文件大小,来判断是否有内容
- if (filesize($filename) >0){
- //读取文件中的内容
- $srcData = file_get_contents($filename);
- }
- }
- //判断内容是否是数组或者对象
- if (is_array($data) || is_object($data)){
- //序列化数据
- $data =serialize($data);
- }
- //判断是否清空源文件中的内容
- if (!$clearFlag){
- //拼装之前的内容到一起
- $data=$srcData.$data;
- }
- //向文件中写入内容
- if (file_put_contents($filename,$data) !==false){
- return true;
- }else{
- return false;
- }
- }
- write_file('4.php','lee',true);
截断内容函数
- //截断内容
- function truncate_file(string $filename,int $length){
- if (is_file($filename) && is_writable($filename)){
- //以r+(读写)的方式打开文件
- $handle = fopen($filename,'r+');
- //判断长度的大小,三元操作符
- $length = $length <0?0:$length;
- ftruncate($handle,$length);
- fclose($handle);
- return true;
- }
- return false;
- }
- truncate_file('test_read.txt',6);