當前位置: 首頁> 最新文章列表> PHP文件讀取與寫入技巧總結

PHP文件讀取與寫入技巧總結

gitbox 2025-06-07

1. 文件讀取技巧

1.1 fopen() 函數

fopen() 函數用於打開一個文件,可以讀取文件內容或寫入新內容。該函數需要兩個參數:文件名和打開模式(只讀、寫入、追加等)。例如,下面的代碼打開一個文件並逐行讀取內容:

 
$file = fopen("example.txt", "r");
while (!feof($file)) {
  echo fgets($file)."";
}
fclose($file);

這裡使用了while 循環配合fgets() 函數逐行讀取文件,feof() 用於檢測是否已到文件末尾,fclose() 則用於關閉文件句柄。

1.2 fread() 函數

如果需要一次性讀取整個文件內容,可以使用fread() 函數。該函數需要文件句柄和讀取的字節數作為參數,如下示例:

 
$file = fopen("example.txt", "r");
echo fread($file, filesize("example.txt"));
fclose($file);

代碼先通過filesize() 獲取文件大小,再用fread() 讀取指定字節數內容。

1.3 file() 函數

file() 函數將文件每一行讀入數組,適合需要逐行處理文本文件的場景。示例如下:

 
$file = file("example.txt");
foreach ($file as $line) {
  echo $line."";
}

通過foreach 循環遍歷數組,輸出每一行內容。

1.4 file_get_contents() 函數

file_get_contents() 是讀取整個文件最簡單快捷的方法,返回文件內容字符串。示例如下:

 
$file = file_get_contents("example.txt");
echo $file;

函數直接返回文件內容,適合快速讀取小文件。

2. 文件寫入技巧

2.1 fwrite() 函數

fwrite() 用於向文件寫入數據,需傳入文件句柄和寫入字符串。示例代碼:

 
$file = fopen("example.txt", "w");
fwrite($file, "Hello World!");
fclose($file);

使用"w" 模式打開文件時會覆蓋原內容,如需追加內容可使用"a" 模式。

2.2 file_put_contents() 函數

file_put_contents() 是向文件寫入字符串的簡便方法,傳入文件名和寫入內容即可,如:

 
file_put_contents("example.txt", "Hello World!");

如果文件不存在,函數會自動創建新文件。

3. 總結

PHP 提供多種文件讀寫函數,常用的包括fopen()、fread()、file()、file_get_contents() 用於讀取,fwrite() 和file_put_contents() 用於寫入。使用時需注意文件權限設置,避免因權限不足導致操作失敗。一般建議優先使用file_get_contents() 和file_put_contents(),它們代碼簡潔、執行效率高,且易於維護。