您的位置:首页 > 编程学习 > > 正文

php数组写法(php文件操作之文件写入字符串、数组的方法分析)

更多 时间:2022-03-28 22:38:17 类别:编程学习 浏览量:2692

php数组写法

php文件操作之文件写入字符串、数组的方法分析

本文实例讲述了php文件操作之文件写入字符串、数组的方法。分享给大家供大家参考,具体如下:

  • 场景一:用文本文档记录一些操作日志,因为对于一些频繁的操作,操作记录的数据量势必会很大,如果用数据库来存储会给数据库带来压力。
  • 场景二:代替输出函数打印一些数据,例如在支付的回调里面不好用echo、var_dump等直观地打印数据出来,就要用到写入文件来记录数据的方式,可以用于排除错误等。

记录当前时间,写入文件:

php数组写法(php文件操作之文件写入字符串、数组的方法分析)

使用file_put_contents()函数(写入字符串)

  • ?
  • 1
  • 2
  • 3
  • 4
  • <?php
  •   $log = "./log.txt"; //文件路径,linux下需要设置可写权限
  •   $text = date('y-m-d h:i:s')."\r\n"; //记录当前时间
  •   file_put_contents($log,$text,file_append); //追加写入,去掉file_append清除文件内容后写入
  • 依次调用fopen()fwrite()fclose()函数(写入字符串)

  • ?
  • 1
  • 2
  • 3
  • 4
  • <?php
  •   $fp = fopen("./log.txt","a+");//打开文件,准备追加写入,w+为清除写入
  •   fwrite($fp, date('y-m-d h:i:s')."\r\n");//写入文件
  •   fclose($fp);//关闭文件
  • *写入数组:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • <?php
  •   $arr = array('0'=>'lws');
  •   $fp = fopen('./log.txt','a+');
  •   fwrite($fp,var_export($arr,true));
  •   fclose($fp);
  • ( 如果报以下错,说明php.ini的时区没有设置好,找到'date.timezone'一行,设置 date.timezone = prc

    warning: date(): it is not safe to rely on the system's timezone settings. you are *required* to use the date.timezone setting or the date_default_timezone_set() function. in case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. we selected the timezone 'utc' for now, but please set date.timezone to select your timezone.

    另外,以上两种文件写入的方式,如果文件不存在都会自动创建该文件,可以省去使用file_exists()函数判断文件是否存在。)

    希望本文所述对大家php程序设计有所帮助。

    原文链接:https://blog.csdn.net/msllws/article/details/80955539

    您可能感兴趣