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

PHP 讀取檔案內容五大方法總結與效能比較

     編輯:PHP 相關知識

PHP 讀取檔案內容五大方法總結與效能比較

實際開發中常需讀取檔案內容,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()可指定精確位移與長度
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved