1.小文件写入 方法一
function writeFile($filePath, $content) { $mode = file_exists($filePath) ? 'a' : 'w'; // 存在就追加,否则新建写入 $targetFile = fopen($filePath, $mode) or die('Unable to open file!'); fwrite($targetFile, $content . "\n"); fclose($targetFile); echo 'Successful write!'; }
优化后: 参见:https://github.com/ningxiaofa/learning_of_php/blob/master/文件写入/simple-echo-content-to-file.php
// 记录日志 --- 常用于打印调试,收集日志信息 $filename = 'log.txt'; $logPath = dirname(__FILE__).'/'.$filename;
function write($file_path, $content) { if(file_exists($file_path)) { //"当前目录中,文件存在",追加 $myfile = fopen($file_path, "a") or die("Unable to open file!"); $txt = "\n" . $content . ' --- '. "【" . date('Y-m-d H:i:s', time())."】"; fwrite($myfile, $txt); //记得关闭流 fclose($myfile); } else { //"当前目录中,文件不存在",新写入 $myfile = fopen($file_path, "w") or die("Unable to open file!"); $txt = $content . ' --- ' . "【" . date('Y-m-d H:i:s', time())."】"; fwrite($myfile, $txt); //记得关闭流 fclose($myfile); } }
write($logPath,'log begin');
简化后
protected static function write($filePath, $content) { $handle = null; // Append when file exists in current directory, else create and write $mode = 'w'; if (file_exists($filePath)) { $mode = 'a'; } $handle = fopen($filePath, $mode) or die("Unable to open file!"); fwrite($handle, $content . ','); fclose($handle); }
扩展: 保证多个PHP进程/线程对同一个文件成功写入 Note: PHP是不支持多线程的,可以使用php的flock加锁函数实现。 Code: https://github.com/ningxiaofa/learning_of_php/blob/master/文件写入/多进程写入同一文件/multiple-processes-write-to-the-same-file.php
<?php function writeFile($filePath, $data){ $handle = fopen($filePath, 'a+'); // 以追加的方式打开文件,返回的是指针 if(!$handle) return; do{ usleep(100);//暂停执行程序,参数是以微秒为单位的 }while(!flock($handle, LOCK_EX)); // 以独享写入方式锁定文件,成功返回TRUE,否则FALSE fwrite($handle, $data."\r\n"); // 以追加的方式写入数据到打开的文件 flock($handle, LOCK_UN); // 解锁,以让别的进程进行锁定 fclose($handle); // 关闭打开的文件指针 }
writeFile('./test.txt','test');
方法二 全部读入内存,使用file_get_contents(); 2.大文件写入[GB级别] 如果没有超过物理内存 TBD 如果超过物理内存 TBD |