fopen() 函數用於打開一個文件,可以讀取文件內容或寫入新內容。該函數需要兩個參數:文件名和打開模式(只讀、寫入、追加等)。例如,下面的代碼打開一個文件並逐行讀取內容:
$file = fopen("example.txt", "r");
while (!feof($file)) {
echo fgets($file)."";
}
fclose($file);
這裡使用了while 循環配合fgets() 函數逐行讀取文件,feof() 用於檢測是否已到文件末尾,fclose() 則用於關閉文件句柄。
如果需要一次性讀取整個文件內容,可以使用fread() 函數。該函數需要文件句柄和讀取的字節數作為參數,如下示例:
$file = fopen("example.txt", "r");
echo fread($file, filesize("example.txt"));
fclose($file);
代碼先通過filesize() 獲取文件大小,再用fread() 讀取指定字節數內容。
file() 函數將文件每一行讀入數組,適合需要逐行處理文本文件的場景。示例如下:
$file = file("example.txt");
foreach ($file as $line) {
echo $line."";
}
通過foreach 循環遍歷數組,輸出每一行內容。
file_get_contents() 是讀取整個文件最簡單快捷的方法,返回文件內容字符串。示例如下:
$file = file_get_contents("example.txt");
echo $file;
函數直接返回文件內容,適合快速讀取小文件。
fwrite() 用於向文件寫入數據,需傳入文件句柄和寫入字符串。示例代碼:
$file = fopen("example.txt", "w");
fwrite($file, "Hello World!");
fclose($file);
使用"w" 模式打開文件時會覆蓋原內容,如需追加內容可使用"a" 模式。
file_put_contents() 是向文件寫入字符串的簡便方法,傳入文件名和寫入內容即可,如:
file_put_contents("example.txt", "Hello World!");
如果文件不存在,函數會自動創建新文件。
PHP 提供多種文件讀寫函數,常用的包括fopen()、fread()、file()、file_get_contents() 用於讀取,fwrite() 和file_put_contents() 用於寫入。使用時需注意文件權限設置,避免因權限不足導致操作失敗。一般建議優先使用file_get_contents() 和file_put_contents(),它們代碼簡潔、執行效率高,且易於維護。