在PHP開發中,文件操作是非常基礎且常用的功能。文件讀取用於獲取文件內容,而文件寫入則是將數據保存到文件中。本文將詳細講解PHP中各種文件讀取與寫入方法,並配合實例代碼,幫助你輕鬆掌握文件操作技巧。
fopen()是PHP中最基礎的文件操作函數,它用於打開文件並返回文件資源句柄。函數需要傳入文件名和打開模式,常用模式包括:
示例代碼:
$file = fopen("file.txt", "r"); if ($file) { while (($line = fgets($file)) !== false) { echo $line; } fclose($file); }
file_get_contents()函數可以一次性將整個文件內容讀入為字符串,使用非常方便。只需傳入文件路徑即可。
$fileContent = file_get_contents("file.txt"); echo $fileContent;
fread()函數通常與fopen()配合使用,用於讀取指定長度的文件內容。接受文件資源和讀取長度兩個參數。
$file = fopen("file.txt", "r"); if ($file) { $content = fread($file, filesize("file.txt")); echo $content; fclose($file); }
fopen()同樣可以打開文件用於寫入,只需將模式設置為"w"(寫入,覆蓋原內容)或"a"(追加內容)。
$file = fopen("file.txt", "w"); if ($file) { fwrite($file, "Hello, World!"); fclose($file); }
file_put_contents()是寫入文件的簡便函數,無需先打開文件,直接傳入文件名和內容即可。
file_put_contents("file.txt", "Hello, World!");
fwrite()函數用於將內容寫入已經打開的文件資源,配合fopen使用。
$file = fopen("file.txt", "w"); if ($file) { fwrite($file, "Hello, World!"); fclose($file); }
本文介紹了PHP中常用的文件讀取和寫入函數,包括fopen、file_get_contents、fread、file_put_contents及fwrite,配合實例演示瞭如何高效地進行文件操作。根據不同需求選擇合適的方法,可以讓文件處理變得簡單又高效。