萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 讀取檔案內容三種方法完整比較

前言

PHP 提供多種讀取檔案方式,適用場景不同。本文整理三種常見方法並比較優缺點。

方法一:fopen + fread(傳統流式,適合大檔)

$filePath = 'text.txt';
if (file_exists($filePath)) {
    if ($fp = fopen($filePath, 'r')) {
        $content = fread($fp, filesize($filePath));
        $content = str_replace("\r\n", "
", $content); echo $content; fclose($fp); } else { echo '檔案無法開啟'; } } else { echo '檔案不存在'; }
  • 優點:可控制讀取位元組數、支援指標移動、記憶體友善(配合迴圈分塊讀取)
  • 缺點:程式碼較冗長

方法二:file_get_contents(最簡潔,適合中小檔)

$filePath = 'text.txt';
$content = file_get_contents($filePath);
$content = str_replace("\r\n", "
", $content); echo $content;
  • 優點:一行搞定、內部最佳化、支援 URL 串流(需 allow_url_fopen=On)
  • 缺點:一次載入整檔到記憶體,超大檔案會 OOM

方法三:fopen + feof 迴圈分塊讀取(大檔、串流處理)

$filePath = 'text.txt';
if (file_exists($filePath) && $fp = fopen($filePath, 'r')) {
    $buffer = 1024;  // 每次 1KB
    $str = '';
    while (!feof($fp)) {
        $str .= fread($fp, $buffer);
    }
    fclose($fp);
    $str = str_replace("\r\n", "
", $str); echo $str; } else { echo '檔案不存在或無法開啟'; }
  • 優點:記憶體佔用固定、可邊讀邊處理(如逐行解析 CSV、日誌)
  • 缺點:程式碼最多

補充:讀取 INI 設定檔

$arr = parse_ini_file('config.ini');  // 回傳關聯陣列
echo $arr['host'] . '
'; echo $arr['username'] . '
'; echo $arr['password'] . '
';

適用於簡單 key-value 設定檔,支援區段(sections)。

選擇建議

檔案大小推薦方法
< 10MBfile_get_contents
10MB ~ 100MBfread 分塊讀取
> 100MBfopen + 迴圈 + 生成器/迭代器處理
INI 設定檔parse_ini_file
copyright © 萬盛學電腦網 all rights reserved