萬盛學電腦網

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

PHP file_get_contents() 讀取遠端資源完整指南:從基礎用法到高效能采集實戰

基本用法

<?php
// 讀取本地檔案
$content = file_get_contents('/path/to/file.txt');

// 讀取遠端 URL (需 php.ini: allow_url_fopen=On)
$url = 'https://api.example.com/data.json';
$json = file_get_contents($url);
$data = json_decode($json, true);
?>

Stream Context 進階控制

透過 stream_context_create() 自訂 HTTP 標頭、方法、超時、SSL 驗證等:

<?php
$options = [
    'http' => [
        'method'        => 'GET',
        'header'        => "User-Agent: MyBot/1.0\r\n" .
                           "Accept: application/json\r\n" .
                           "Authorization: Bearer $token\r\n",
        'timeout'       => 10,          // 秒
        'ignore_errors' => true,        // 取得 4xx/5xx 回應內容
        'follow_location' => 1,         // 跟隨重導向
        'max_redirects' => 5,
    ],
    'ssl' => [
        'verify_peer'      => true,
        'verify_peer_name' => true,
        // 'cafile' => '/path/to/cacert.pem',  // 自訂 CA
    ],
];

$context = stream_context_create($options);
$response = file_get_contents('https://api.example.com/data', false, $context);

if ($response === false) {
    $error = error_get_last();
    throw new RuntimeException("HTTP 請求失敗: {$error['message']}");
}

$httpCode = $http_response_header ? (int)explode(' ', $http_response_header[0])[1] : 0;
if ($httpCode >= 400) {
    throw new RuntimeException("HTTP $httpCode: $response");
}

$data = json_decode($response, true);
?>

大檔案分塊處理 (避免記憶體耗盡)

<?php
function readLargeFileChunked(string $url, callable $callback, int $chunkSize = 8192): void {
    $context = stream_context_create(['http' => ['follow_location' => 1]]);
    $handle = fopen($url, 'rb', false, $context);
    if (!$handle) throw new RuntimeException("無法開啟: $url");
    
    while (!feof($handle)) {
        $chunk = fread($handle, $chunkSize);
        if ($chunk === '') break;
        $callback($chunk);
    }
    fclose($handle);
}

// 使用:逐行處理 CSV
readLargeFileChunked('https://example.com/big.csv', function($chunk) {
    static $buffer = '';
    $buffer .= $chunk;
    $lines = explode("\n", $buffer);
    $buffer = array_pop($lines);  // 最後一行可能不完整
    foreach ($lines as $line) {
        $fields = str_getcsv($line);
        processCsvRow($fields);
    }
});
?>

采集實戰:結構化資料解析

<?php
/**
 * 采集遠端結構化資料 (每行: id|name|time|email)
 */
function fetchRemoteData(string $url): array {
    $content = file_get_contents($url);
    if ($content === false) return [];
    
    $lines = explode("\r\n", trim($content));
    $result = [];
    
    foreach ($lines as $line) {
        if ($line === '') continue;
        [$id, $name, $time, $email] = explode('|', $line);
        
        if ($id === '-1') continue;  // 錯誤標記行
        
        $result[] = [
            'id'    => (int)$id,
            'name'  => $name,
            'time'  => $time,
            'email' => $email,
        ];
    }
    return $result;
}
?>

HTML 頁面采集與正則提取

<?php
function scrapeWeather(string $province, string $city): ?string {
    $url = "https://weather.example.com/$province/$city.html";
    
    $context = stream_context_create([
        'http' => [
            'timeout' => 10,
            'header' => "User-Agent: Mozilla/5.0 (compatible; WeatherBot/1.0)\r\n",
        ],
    ]);
    
    $html = @file_get_contents($url, false, $context);
    if ($html === false) return null;
    
    // 提取預報區塊
    if (preg_match('/五天天氣趨勢預報<\/B>(.*?)請輸入輸入市/si', $html, $m)) {
        $content = $m[1];
        // 修正相對路徑圖片
        $content = preg_replace('~/image/~', 'https://weather.example.com/image/', $content);
        // 轉換連結為本站路由
        $content = preg_replace('~/weather/(\w+)/(\w+)\.htm~', '$2.html?pro=$1', $content);
        return $content;
    }
    return null;
}
?>

file_get_contents vs cURL 對比

特性file_get_contentscURL
語法簡潔度高較繁瑣
HTTP 功能完整度基本 (需 Stream Context)完整 (多重請求、Cookie 罐、進度條、HTTP/2)
大檔案串流需 fopen/fread原生支援
效能較低 (內部仍用 streams)較高、可複用連線
錯誤處理回傳 false + error_get_last()詳細錯誤代碼、curl_error()
並發請求不支援支援 curl_multi_*

選擇建議

  • 簡單 GET、小檔案、JSON API:file_get_contents + Stream Context 足夠。
  • 複雜 HTTP 需求 (POST、Cookie、認證、重試、並發、大檔案):cURL 或 GuzzleHttp/Client (現代 HTTP 客戶端庫)。
  • 生產環境建議統一使用 Guzzle,提供 PSR-18/PSR-17 相容、中介軟體、重試策略、非同步支援。

Guzzle 現代寫法範例

<?php
use GuzzleHttp\Client;

$client = new Client([
    'base_uri' => 'https://api.example.com/',
    'timeout'  => 10,
    'headers'  => ['User-Agent' => 'MyApp/1.0'],
]);

try {
    $response = $client->get('data.json', ['query' => ['limit' => 100]]);
    $data = json_decode($response->getBody()->getContents(), true);
} catch (GuzzleHttp\Exception\RequestException $e) {
    // 處理連線錯誤、HTTP 錯誤、逾時
    logError($e->getMessage());
}
?>

根據專案複雜度選擇適當工具,簡單場景 file_get_contents 即可,複雜采集系統建議引入 Guzzle 獲得企業級可靠度。

copyright © 萬盛學電腦網 all rights reserved