萬盛學電腦網

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

PHP 取得網頁標題三種方法:cURL、file()、file_get_contents 完整比較

遠端抓取網頁並提取 <title> 內容,三種常用方式各有優缺點。

方法一:cURL(推薦,功能最完整)

<?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');
?>
</code></pre>

<h2>方法二:file() 陣列讀取</h2>
<pre><code><?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>(.*?)<\/title>/is', $html, $m)) return trim($m[1]);
    return false;
}
?>
</code></pre>
<p>需 <code>allow_url_fopen = On</code>,無法設定 Timeout、User-Agent、Cookie 等進階選項。</p>

<h2>方法三:file_get_contents()</h2>
<pre><code><?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, '<title>');
    if ($start === false) return false;
    $start += 7;
    $end = stripos($html, '', $start);
    if ($end === false) return false;
    return trim(substr($html, $start, $end - $start));
}
?>

比較總結

特性cURLfile()file_get_contents
支援 HTTPS✅✅ (需 openssl)✅ (需 openssl)
自訂 Header/UA✅❌❌ (需 stream_context)
Cookie/Session✅❌❌ (需 stream_context)
Timeout 控制✅❌❌ (需 stream_context)
重導向追蹤✅⚠️ 部分⚠️ 部分
效能/記憶體可串流全載入陣列全載入字串
推薦度⭐⭐⭐⭐⭐⭐

建議

生產環境統一使用 cURL,封裝為可重用類別,支援並發(curl_multi)、快取、錯誤重試、編碼自動偵測(mb_detect_encoding)。

copyright © 萬盛學電腦網 all rights reserved