QQ咨询 官方微信

添加微信好友

官方小程序

百度小程序

微信小程序

头条小程序

关于我们

PHP基础

php写入txt文件的两种方法

 shitouadmin  2024-07-08 08:14:02
调试的时候有时候需要把错误信息写入txt文件,有两种常用办法
1、通过file_put_contents像记事本中追加数据
  1. $filePath = 'log.txt'
  2. $data = "测试数据\r\n"
  3. file_put_contents($filePath, $data, FILE_APPEND); 
FILE_APPEND表示是追加内容

2、通过fwrite方式写入
  1. $fp = fopen("log.txt",'a+'); 
  2. $txt = "Bill Gates\n";
  3. fwrite($fp,$text); 
  4. 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文件是否存在,不存在则自动创建
  1. $file = "log.txt"
  2. if(!is_dir($file)){ 
  3.     mkdir($file,0777,true); 
  4. }    
2、判断路径是否存在,不存在则全部创建
  1. function mkdirs($dir, $mode = 0777) 
  2.     if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE; 
  3.     if (!mkdirs(dirname($dir), $mode)) return FALSE; 
  4.     return @mkdir($dir, $mode); 
  5. $file = "log/log.txt"
  6. if(!file_exists($file)){ 
  7.     mkdirs($file); 





¥ 打赏
×
如果您觉得文章帮助了您就打赏一下吧
非常感谢你的打赏,我们将继续分享更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

本文《php写入txt文件的两种方法》发布于石头博客文章,作者:shitouadmin,如若转载,请注明出处:https://www.pweb123.com/html/php/1032.html,否则禁止转载,谢谢配合!

文章点评

我来说两句 已有0条评论
点击图片更换

添加微信好友

添加微信好友

微信小程序

百度小程序