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

PHP 遠端抓取 HTML 並擷取標題/內容實作

     編輯:PHP 綜合知識

基本抓取與擷取

<?php
$url = 'https://www.baidu.com';
$html = file_get_contents($url);

// 編碼轉換 (目標站為 GBK)
$html = iconv('GBK', 'UTF-8//IGNORE', $html);

// 擷取  內容
$start = strpos($html, '<title>');
$end   = strpos($html, '');
if ($start !== false && $end !== false) {
    $title = substr($html, $start + 7, $end - $start - 7);
    echo "標題: $title";
}

// 字串替換範例
$html = str_replace(['百度一下', '{hello}'], ['自訂標題', 'jb51.net!'], $html);
echo $html;
?>

進階:cURL 抓取 (支援 Header、Cookie、Timeout、User-Agent)

function fetchUrl(string $url, int $timeout = 10): string|false
{
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Bot)',
        CURLOPT_CONNECTTIMEOUT => $timeout,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_SSL_VERIFYPEER => false, // 僅測試用,生產請驗證
        CURLOPT_ENCODING => 'gzip,deflate', // 自動解壓
    ]);
    $content = curl_exec($ch);
    $errno = curl_errno($ch);
    curl_close($ch);
    return $errno ? false : $content;
}

$html = fetchUrl('https://www.example.com');
if ($html) {
    // 後續解析...
}

建議使用 DOMDocument 解析而非正則

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('' . $html); // 強制 UTF-8
libxml_clear_errors();

$title = $dom->getElementsByTagName('title')->item(0)?->textContent ?? '';
$links = [];
foreach ($dom->getElementsByTagName('a') as $a) {
    $links[] = [
        'text' => $a->textContent,
        'href' => $a->getAttribute('href')
    ];
}

法律與道德提醒

  • 遵守 robots.txt 爬蟲協定
  • 控制請求頻率 (sleep/usleep),避免對目標站造成壓力
  • 僅供個人學習研究,勿大量抓取或再散布受版權保護內容
  • 商業用途請取得授權或使用官方 API
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved