PHP 提供多種讀取檔案的函式,各有優缺點。本文詳細比較 fread、fgets、fgetss、file、readfile、file_get_contents、fpassthru、parse_ini_file 八種方法的語法、行為差異與效能特徵,助你選出最適合的方案。
$handle = fopen("file.txt", "r");
$content = fread($handle, filesize("file.txt")); // 本地檔案可一次讀完
fclose($handle);
遠端/流檔案無法取得大小,需搭配 feof() 迴圈:
$handle = fopen('https://example.com', 'r');
$content = '';
while (!feof($handle)) $content .= fread($handle, 8192);
fclose($handle);
$handle = fopen('file.txt', 'r');
while (!feof($handle)) echo fgets($handle, 1024);
fclose($handle);
預設長度 1024 位元組,PHP 4.3+ 可省略長度參數讀取完整行。
echo fgetss($handle, 1024, '<br>'); // 保留 <br> 標籤
$lines = file('file.txt');
foreach ($lines as $num => $line) echo "Line $num: $line";
含換行符,可用 rtrim() 移除。
$size = readfile('file.txt'); // 適合圖片、PDF 直接下載輸出
$content = file_get_contents('file.txt');
支援 stream_context 設定 HTTP 超時、Header 等:
$ctx = stream_context_create(['http' => ['timeout' => 1]]);
echo file_get_contents('https://example.com', 0, $ctx);
fseek($handle, 1024); // 跳過前 1KB fpassthru($handle); // 輸出剩餘內容
$config = parse_ini_file('config.ini', true); // true 保留區段結構
| 函式 | 適用場景 | 效能 |
|---|---|---|
| file_get_contents | 中小型檔案整體讀取、遠端 HTTP 獲取 | ⭐⭐⭐⭐⭐ (最快) |
| readfile | 直接輸出二進位檔(圖片/下載) | ⭐⭐⭐⭐⭐ |
| fread/fgets | 大檔案分塊讀取、逐行處理 | ⭐⭐⭐ |
| file | 需逐行陣列處理的小型文字檔 | ⭐⭐⭐ |
| fpassthru | 需從特定位移開始輸出 | ⭐⭐⭐ |
| parse_ini_file | INI 設定檔解析 | 專用 |
fopen 模式加 b(如 rb),增強跨平台相容性。allow_url_fopen 需在 php.ini 開啟才能用 URL 開啟遠端檔案。urlencode() 編碼。