實際開發中常需讀取檔案內容,PHP 提供多種方式,各有適用場景。本文匯總五種主流方法並附帶關鍵細節提醒:記得用 fclose($fp) 釋放資源。
fread() 一次性讀取全檔<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path, "r");
$str = fread($fp, filesize($file_path)); // 指定長度讀完整檔
echo str_replace("\r\n", "<br />", $str);
fclose($fp);
}
?>
⚠ 需預先取得檔案大小,大檔案可能佔用大量記憶體。
file_get_contents() 最簡潔(推薦中小檔案)<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$str = file_get_contents($file_path); // 直接讀入字串
echo str_replace("\r\n", "<br />", $str);
}
?>
內部已封裝開啟/讀取/關閉,代碼最乾淨,效能優秀,首選方案。
fread() 分塊循環讀取(大檔案必備)<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path, "r");
$str = "";
$buffer = 1024; // 每次 1KB
while(!feof($fp)){
$str .= fread($fp, $buffer);
}
echo str_replace("\r\n", "<br />", $str);
fclose($fp);
}
?>
適合超大檔案(如日誌、匯出資料),避免記憶體飆升。
file() 逐行讀入陣列<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$file_arr = file($file_path); // 每行含換行符
foreach($file_arr as $value){
echo $value . "<br />";
}
}
?>
返回陣列,每行保留換行符,適合逐行處理邏輯(如 CSV 解析)。
fgets() 逐行流式讀取<?php
$file_path = "test.txt";
if(file_exists($file_path)){
$fp = fopen($file_path, "r");
$str = "";
while(!feof($fp)){
$str .= fgets($fp); // 預設 1KB,可指定長度
}
echo str_replace("\r\n", "<br />", $str);
fclose($fp);
}
?>
類似方法四但流式處理,記憶體佔用更平穩。
| 場景 | 推薦方法 | 理由 |
|---|---|---|
| 中小檔案、單純讀取全文 | file_get_contents() | 代碼最少、效能佳 |
| 超大檔案(>100MB) | fread() 分塊 / fgets() | 流式處理,恆定記憶體 |
| 需逐行邏輯處理 | file() 或 fgets() | 天然按行分割 |
| 二進位檔案/精確位元組控制 | fread() | 可指定精確位移與長度 |