1、通过file_put_contents像记事本中追加数据
FILE_APPEND表示是追加内容
- $filePath = 'log.txt';
- $data = "测试数据\r\n";
- file_put_contents($filePath, $data, FILE_APPEND);
2、通过fwrite方式写入
打开模式:
- $fp = fopen("log.txt",'a+');
- fwrite($fp,$text);
- fclose($fp);
mode |
说明 |
---|---|
'r' |
只读方式打开,将文件指针指向文件头。 |
'r+' |
读写方式打开,将文件指针指向文件头。 |
'w' |
写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 |
'w+' |
读写方式打开,否则行为同 'w' 。 |
'a' |
写入方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。在这种情况下,fseek() 没有效果,写入总是追加。 |
'a+' |
读写方式打开,将文件指针指向文件末尾。如果文件不存在则尝试创建之。在这种情况下,fseek() 只相应读取位置,写入总是追加。 |
'x' |
创建并以写入方式打开,将文件指针指向文件头。如果文件已存在,则 fopen() 调用失败并返回 false ,并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。 |
'x+' |
创建并以读写方式打开,其他的行为和 'x' 一样。 |
'c' |
Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w' ), nor the call to this function fails (as is the case with 'x' ). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested). |
'c+' |
Open the file for reading and writing; otherwise it has the same behavior as 'c' . |
'e' |
Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems. |
扩展:
1、判断txt文件是否存在,不存在则自动创建
2、判断路径是否存在,不存在则全部创建
- $file = "log.txt";
- if(!is_dir($file)){
- mkdir($file,0777,true);
- }
- function mkdirs($dir, $mode = 0777)
- {
- if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
- if (!mkdirs(dirname($dir), $mode)) return FALSE;
- return @mkdir($dir, $mode);
- }
- $file = "log/log.txt";
- if(!file_exists($file)){
- mkdirs($file);
- }
文章点评