遠端抓取網頁並提取 <title> 內容,三種常用方式各有優缺點。
<?php
function getTitleCurl($url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_TIMEOUT => 10,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Bot)',
CURLOPT_SSL_VERIFYPEER => false, // 僅測試用,生產請驗證憑證
]);
$html = curl_exec($ch);
curl_close($ch);
if (!$html) return false;
// 編碼偵測與轉換
if (stripos($html, 'utf-8') === false && stripos($html, 'utf8') === false) {
$html = iconv('GBK', 'UTF-8//IGNORE', $html);
}
if (preg_match('/(.*?)<\/title>/is', $html, $m)) {
return trim($m[1]);
}
return false;
}
echo getTitleCurl('https://www.jb51.net');
?>
<?php
function getTitleFile($url) {
$lines = @file($url, FILE_IGNORE_NEW_LINES);
if (!$lines) return false;
$html = implode('', $lines);
if (stripos($html, 'utf-8') === false) $html = iconv('GBK', 'UTF-8//IGNORE', $html);
if (preg_match('/(.*?)<\/title>/is', $html, $m)) return trim($m[1]);
return false;
}
?>
需 allow_url_fopen = On,無法設定 Timeout、User-Agent、Cookie 等進階選項。
<?php
function getTitleFGC($url) {
$html = @file_get_contents($url);
if (!$html) return false;
if (stripos($html, 'utf-8') === false) $html = iconv('GBK', 'UTF-8//IGNORE', $html);
$start = stripos($html, '');
if ($start === false) return false;
$start += 7;
$end = stripos($html, ' ', $start);
if ($end === false) return false;
return trim(substr($html, $start, $end - $start));
}
?>
| 特性 | cURL | file() | file_get_contents |
|---|---|---|---|
| 支援 HTTPS | ✅ | ✅ (需 openssl) | ✅ (需 openssl) |
| 自訂 Header/UA | ✅ | ❌ | ❌ (需 stream_context) |
| Cookie/Session | ✅ | ❌ | ❌ (需 stream_context) |
| Timeout 控制 | ✅ | ❌ | ❌ (需 stream_context) |
| 重導向追蹤 | ✅ | ⚠️ 部分 | ⚠️ 部分 |
| 效能/記憶體 | 可串流 | 全載入陣列 | 全載入字串 |
| 推薦度 | ⭐⭐⭐ | ⭐ | ⭐⭐ |
生產環境統一使用 cURL,封裝為可重用類別,支援並發(curl_multi)、快取、錯誤重試、編碼自動偵測(mb_detect_encoding)。