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

PHP 文件讀取八大姿勢完全指南:從 fread 到 parse_ini_file 的場景化選型

     編輯:PHP 相關知識

概覽:八種方法對比表

函數/方法返回類型適用場景性能/特點
fread()string二進制/大文件、需控制讀取長度、流式讀取底層控制力最強,需手動 fopen/fclose
fgets()string(單行)逐行處理大文本(日志、CSV)內存友好,默認 1KB 行長
fgetss()string(單行)逐行讀取並剝離 HTML/PHP 標籤可保留指定標籤,解析類文本
file()array(行數組)小/中型文本整體讀入、需隨機訪問行自動處理換行,含換行符
readfile()int(字節數)直接輸出文件到瀏覽器(下載、圖片代理)不經 PHP 內存緩衝,極快
file_get_contents()string全文讀入字符串、支援流上下文(超時、Header)性能優於 fopen 系,首選通用讀取
fpassthru()int(字節數)從當前指針位置輸出剩餘內容到瀏覽器配合 fseek 實現斷點續傳/分片輸出
parse_ini_file()array(結構化)解析 INI 配置文件,支援節專用場景,自動類型轉換

詳細用法與代碼示例

1. fread() — 精確控制讀取長度

<?php
// 本地文件:一次性讀取
$handle = fopen('/usr/local/something.txt', 'rb');  // 二進制模式
$contents = fread($handle, filesize('/usr/local/something.txt'));
fclose($handle);

// 遠程/流文件:分塊循環讀取(無 filesize)
$handle = fopen('https://www.baidu.com', 'r');
$content = '';
while (!feof($handle)) {
    $content .= fread($handle, 8192);
}
fclose($handle);
// 或利用 fread 返回 false 判斷結束
while (false !== ($chunk = fread($handle, 8192))) {
    $content .= $chunk;
}
?>

2. fgets() / fgetss() — 逐行處理

<?php
$handle = fopen('./file.txt', 'r');
while (!feof($handle)) {
    echo fgets($handle, 1024);  // 保留換行符
}
fclose($handle);

// fgetss: 自動去除標籤,第三參數保留允許標籤
$handle = fopen('./file.txt', 'r');
while (!feof($handle)) {
    echo fgetss($handle, 1024, '<br><p>');
}
fclose($handle);
?>

3. file() — 讀入數組

<?php
$lines = file('./file.txt');
foreach ($lines as $num => $line) {
    echo "Line " . ($num + 1) . ": " . rtrim($line) . "<br>";
}
?>

4. readfile() — 直接輸出

<?php
$size = readfile('./file.txt');  // 直接輸出到瀏覽器
echo "Transferred $size bytes";
?>

5. file_get_contents() — 現代首選

<?php
// 基本用法
$content = file_get_contents('./file.txt');

// 遠程請求帶超時上下文
$ctx = stream_context_create([
    'http' => [
        'timeout' => 5,  // 秒
        'header'  => "User-Agent: MyApp/1.0\r\n"
    ]
]);
$content = file_get_contents('https://api.example.com/data', 0, $ctx);
?>

性能提示:file_get_contents 內部使用內存映射(mmap),大文件讀取顯著快於 fopen/fread 組合。readfile 直接輸出無內存佔用,極適合大文件下載代理。

6. fpassthru() — 指針位置輸出

<?php
header('Content-Type: text/html; charset=utf-8');
$handle = fopen('./test2.php', 'r');
fseek($handle, 1024);  // 跳過前 1KB
fpassthru($handle);    // 輸出剩餘
?>

7. parse_ini_file() — 配置文件解析

test.ini:

; 註釋
[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = "/usr/local/bin"
URL = "https://www.example.com/~username"

test.php:

<?php
$config = parse_ini_file('./test.ini', true);  // true = 解析節
print_r($config);
/* 輸出:
Array
(
    [first_section] => Array([one]=>1 [five]=>5 [animal]=>BIRD)
    [second_section] => Array([path]=>/usr/local/bin [URL]=>https://...)
)
*/
?>

四大避坑指南

  1. 二進制文件加 b 標志:fopen($file, 'rb'),跨平台兼容(Windows 必須,Linux 無害);
  2. allow_url_fopen:控制遠程協議封裝,php.ini 級別,生產建議 Off;
  3. URL 特殊字符編碼:fopen('https://example.com/'.urlencode($path));
  4. 大文件內存保護:超過可用內存時改用 fread 分塊或 readfile 直接輸出,避免 file_get_contents 撐爆內存。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved