本文實例講述了php文件操作之文件寫入字符串、數組的方法。分享給大家供大家參考,具體如下:
記錄當前時間,寫入文件:
使用file_put_contents()
函數(寫入字符串)
<?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()
函數(寫入字符串)
<?php $fp = fopen("./log.txt","a+");//打開文件,準備追加寫入,w+為清除寫入 fwrite($fp, date('Y-m-d H:i:s')."/r/n");//寫入文件 fclose($fp);//關閉文件
*寫入數組:
<?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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選