首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 讀取檔案八大方法總結:fread、fgets、fgetss、file、readfile、file_get_contents、fpassthru、parse_ini_file

     編輯:PHP 綜合知識

八大方法對比表

函數回傳特性適用場景
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()
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved