PHP 提供多種讀取檔案方式,適用場景不同。本文整理三種常見方法並比較優缺點。
$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 '檔案不存在';
}
$filePath = 'text.txt';
$content = file_get_contents($filePath);
$content = str_replace("\r\n", "
", $content);
echo $content;
allow_url_fopen=On)$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 '檔案不存在或無法開啟';
}
$arr = parse_ini_file('config.ini'); // 回傳關聯陣列
echo $arr['host'] . '
';
echo $arr['username'] . '
';
echo $arr['password'] . '
';
適用於簡單 key-value 設定檔,支援區段(sections)。
| 檔案大小 | 推薦方法 |
|---|---|
| < 10MB | file_get_contents |
| 10MB ~ 100MB | fread 分塊讀取 |
| > 100MB | fopen + 迴圈 + 生成器/迭代器處理 |
| INI 設定檔 | parse_ini_file |