八大方法對比表
| 函數 | 回傳 | 特性 | 適用場景 |
fread() | 字串 | 指定長度、二進制安全、需 fopen | 固定長度讀取、二進制檔案 |
fgets() | 字串 | 單行、含換行符、長度可限制 | 逐行處理大檔案、日誌分析 |
fgetss() | 字串 | 同 fgets 但剝離 HTML/PHP 標籤 | 不受信任文字檔安全顯示 |
file() | 陣列 | 整檔按行讀入陣列、含換行 | 小檔案快速處理、配合 foreach |
readfile() | int(位元組數) | 直接輸出到輸出緩衝、不佔記憶體 | 檔案下載、圖片輸出、大檔案傳輸 |
file_get_contents() | 字串 | 整檔讀入字串、支援 offset/maxlen、context | 最通用、效能佳、遠端 URL 支援 |
fpassthru() | int | 從當前指標輸出到 EOF | 配合 fseek 部分輸出、斷點續傳 |
parse_ini_file() | 陣列 | 解析 INI 格式、支援區段 | 設定檔讀取 |
詳細範例
1. fread - 讀取整檔(需已知大小)
$fp = fopen('data.bin', 'rb');
$content = fread($fp, filesize('data.bin'));
fclose($fp);
2. fgets - 逐行讀取
$fp = fopen('log.txt', 'r');
while (!feof($fp)) {
echo fgets($fp, 1024);
}
fclose($fp);
3. fgetss - 安全輸出
$fp = fopen('user_input.txt', 'r');
while (!feof($fp)) {
echo fgetss($fp, 1024, '
'); // 保留 br、b 標籤
}
fclose($fp);
4. file - 陣列化
$lines = file('config.txt');
foreach ($lines as $i => $line) {
echo ($i+1) . ': ' . rtrim($line) . '
';
}
5. readfile - 直接輸出(下載)
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="data.zip"');
readfile('data.zip'); // 不佔 PHP 記憶體
6. file_get_contents - 現代首選
// 本地
$content = file_get_contents('data.json');
// 遠端含逾時
$ctx = stream_context_create(['http' => ['timeout' => 5]]);
$content = file_get_contents('https://api.example.com/data', 0, $ctx);
7. fpassthru - 部分輸出
$fp = fopen('large.mp4', 'rb');
fseek($fp, 1024*1024); // 跳過 1MB
fpassthru($fp); // 輸出剩餘
8. parse_ini_file - 設定檔
// config.ini
; 註解
[database]
host = localhost
port = 3306
[redis]
host = 127.0.0.1
// PHP
$config = parse_ini_file('config.ini', true); // true 保留區段
/*
Array(
[database] => Array([host]=>localhost [port]=>3306)
[redis] => Array([host]=>127.0.0.1)
)
*/
關鍵注意事項
- 二進制安全: 模式加
b(rb/wb),跨平台相容
- 遠端 URL: 需
allow_url_fopen=On,特殊字元用 urlencode()
- 效能排序:
file_get_contents ≈ readfile > fread > file > fgets(大檔案)
- 記憶體:
readfile、fpassthru 直接輸出不佔記憶體,適合大檔下載
- INI 保留字:
null,yes,no,true,false、{ } | & ~ ! [ ] ( ) " 不可作鍵名
選型建議
- 讀取 JSON/設定/小文字檔 →
file_get_contents()
- 逐行處理大日誌 →
fgets() 或 SplFileObject
- 檔案下載/圖片輸出 →
readfile()
- 二進制固定長度 →
fread()
- INI 設定檔 →
parse_ini_file()
- 需移除標籤的用戶內容 →
fgetss()