<?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_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;
}
?>
<?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 | cURL |
|---|---|---|
| 語法簡潔度 | 高 | 較繁瑣 |
| HTTP 功能完整度 | 基本 (需 Stream Context) | 完整 (多重請求、Cookie 罐、進度條、HTTP/2) |
| 大檔案串流 | 需 fopen/fread | 原生支援 |
| 效能 | 較低 (內部仍用 streams) | 較高、可複用連線 |
| 錯誤處理 | 回傳 false + error_get_last() | 詳細錯誤代碼、curl_error() |
| 並發請求 | 不支援 | 支援 curl_multi_* |
file_get_contents + Stream Context 足夠。<?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 獲得企業級可靠度。