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

PHP 批量查詢搜狗 Sogou 排名實作範例

     編輯:PHP 綜合知識

前言

搜狗(Sogou)提供簡易排名查詢介面,可透過 HTTP GET 請求批量檢查網域排名。本文示範從檔案讀取網域清單、逐一查詢、解析結果、篩選高排名網域的完整流程。

一、基本查詢邏輯

<?php
// sogou_rank_check.php
date_default_timezone_set('Asia/Taipei');
header('Content-Type: text/html; charset=utf-8');

// 1. 讀取網域清單(每行一個域名)
$listFile = __DIR__ . '/domains.txt';
if (!is_file($listFile)) die("找不到 $listFile");

$domains = array_filter(array_map('trim', file($listFile, FILE_IGNORE_NEW_LINES)));
if (!$domains) die("清單為空");

echo "<h3>共 " . count($domains) " 個域名開始查詢...</h3><pre>";

$rankThreshold = 2;  // 只顯示排名 > 2 的
$results = [];

foreach ($domains as $domain) {
    // 搜狗排名查詢 API(非官方,可能失效)
    $url = "https://rank.ie.sogou.com/sogourank.php?ur=" . urlencode("https://{$domain}/");
    
    $response = @file_get_contents($url);
    if ($response === false) {
        echo "[ERROR] $domain - 請求失敗\n";
        continue;
    }
    
    // 回傳格式:sogourank=數字
    $rankStr = str_replace('sogourank=', '', trim($response));
    $rank = (int)$rankStr;
    
    $results[$domain] = $rank;
    
    if ($rank > $rankThreshold) {
        echo "[HIGH] $domain - 排名: $rank\n";
    } else {
        echo "[LOW]  $domain - 排名: $rank\n";
    }
    
    // 禮貌延遲,避免被封 IP
    usleep(200000);  // 0.2 秒
}

echo "</pre><h3>查詢完成</h3>";
?>

二、進階:cURL 版(支援超時、重試、並發)

<?php
function checkSogouRankCurl($domain, $timeout = 5, $retries = 2) {
    $url = "https://rank.ie.sogou.com/sogourank.php?ur=" . urlencode("https://{$domain}/");
    
    for ($attempt = 1; $attempt <= $retries; $attempt++) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_CONNECTTIMEOUT => 3,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; SogouRankChecker/1.0)',
            CURLOPT_FOLLOWLOCATION => true,
        ]);
        
        $response = curl_exec($ch);
        $errno = curl_errno($ch);
        curl_close($ch);
        
        if ($errno === 0 && $response !== false) {
            $rank = (int)str_replace('sogourank=', '', trim($response));
            return $rank >= 0 ? $rank : null;
        }
        
        if ($attempt < $retries) usleep(500000);  // 重試前等待
    }
    return null;  // 所有重試失敗
}

// 批量查詢
$domains = ['example.com', 'google.com', 'github.com'];
foreach ($domains as $domain) {
    $rank = checkSogouRankCurl($domain);
    echo "$domain: " . ($rank !== null ? "排名 $rank" : "查詢失敗") . "\n";
}
?>

三、並發查詢(cURL Multi,大幅提速)

<?php
function checkSogouRankMulti($domains, $concurrency = 10) {
    $results = [];
    $mh = curl_multi_init();
    $handles = [];
    
    // 初始化所有 handle
    foreach ($domains as $domain) {
        $url = "https://rank.ie.sogou.com/sogourank.php?ur=" . urlencode("https://{$domain}/");
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_USERAGENT => 'Mozilla/5.0',
        ]);
        curl_multi_add_handle($mh, $ch);
        $handles[$domain] = $ch;
    }
    
    // 執行多路複用
    $running = null;
    do {
        curl_multi_exec($mh, $running);
        curl_multi_select($mh, 0.1);
    } while ($running > 0);
    
    // 收集結果
    foreach ($handles as $domain => $ch) {
        $response = curl_multi_getcontent($ch);
        $errno = curl_errno($ch);
        if ($errno === 0 && $response) {
            $rank = (int)str_replace('sogourank=', '', trim($response));
            $results[$domain] = $rank >= 0 ? $rank : null;
        } else {
            $results[$domain] = null;
        }
        curl_multi_remove_handle($mh, $ch);
    }
    curl_multi_close($mh);
    
    return $results;
}

// 使用
$domains = array_map('trim', file('domains.txt'));
$results = checkSogouRankMulti($domains, 20);
print_r($results);
?>

四、結果儲存與報表

<?php
// 儲存 CSV
$fp = fopen('sogou_rank_' . date('Ymd') . '.csv', 'w');
fputcsv($fp, ['Domain', 'Rank', 'CheckedAt']);
foreach ($results as $domain => $rank) {
    fputcsv($fp, [$domain, $rank ?? 'FAILED', date('Y-m-d H:i:s')]);
}
fclose($fp);

// 統計
$valid = array_filter($results, fn($r) => $r !== null);
$highRank = array_filter($valid, fn($r) => $r > 2);
echo "成功: " . count($valid) . "/" . count($results) . "\n";
echo "高排名(>2): " . count($highRank) . "\n";
?>

五、注意事項與法律提醒

  • 非官方 API: rank.ie.sogou.com 為非公開介面,隨時可能變更或封鎖。
  • 頻率控制: 單 IP 短時間大量請求會被封禁,建議 usleep(200000) 或使用代理池。
  • 排名定義: 搜狗排名數值含義不明確(可能為權重、收錄頁數、流量估值),僅供參考。
  • 法律合規: 批量查詢屬於爬蟲行為,請遵守 robots.txt、搜狗服務條款,勿用於商業監控未經授權。

六、替代方案

方案優點缺點
官方站長平台 API權威、穩定、免費額度需驗證網站擁有權、配額限制
第三方 SEO 工具功能豐富、歷史趨勢、關鍵字分析付費、API 限制
自建爬蟲完全控制、無限制維護成本高、反爬蟲對抗

小結

PHP 批量查詢搜狗排名核心:file_get_contents/cURL 發請求 → 解析 sogourank=數字 → 篩選輸出。生產環境建議:使用 cURL Multi 並發、加入重試機制、儲存歷史趨勢、配合代理池輪換 IP、遵守頻率限制與法律規範。長期監控請改用官方站長平台或專業 SEO 服務。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved