萬盛學電腦網

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

PHP 透過站長之家 API 獲取 IP 歸屬地(含國外 IP 優化)

前言

IP 歸屬地查詢常用於用戶畫像、風控、內容分發。免費介面中站長之家相對詳細(含國外 IP),本文示範 PHP 爬取解析其結果頁面,並提供正則提取關鍵資訊。

實作代碼

<?php
function getIpLocation($ip) {
    $url = "https://tool.chinaz.com/IP/?IP=" . urlencode($ip);
    $html = @file_get_contents($url);
    if (!$html) return ['ip' => $ip, 'location' => '查詢失敗'];

    // 目標結構: ==>> 地址信息 </strong><br />
    $pattern = '/==>>.+?<\/strong><br \/>/';
    if (!preg_match_all($pattern, $html, $matches)) {
        return ['ip' => $ip, 'location' => '解析失敗'];
    }

    $locations = [];
    foreach ($matches[0] as $m) {
        // 移除標記標籤
        $clean = preg_replace('/(==>>)|(==>>\s)/', '', $m);
        $clean = strip_tags($clean);
        $locations[] = trim($clean);
    }
    return [
        'ip' => $ip,
        'location' => implode('; ', $locations),
        'raw' => $locations
    ];
}

// 使用範例
$ips = ['4.4.44.4', '8.8.8.8', '114.114.114.114', '220.181.38.148'];
foreach ($ips as $ip) {
    $result = getIpLocation($ip);
    echo "{$result['ip']} => {$result['location']}<br/>";
}
?>

輸出範例

4.4.44.4 => 美國
8.8.8.8 => 美國 加利福尼亞州 聖克拉拉縣 蒙德維爾 Google DNS 伺服器
114.114.114.114 => 中國 江蘇 南京 電信
220.181.38.148 => 中國 北京 百度

生產環境建議

  • 本地資料庫:下載 IP2Location、GeoIP2 离线資料庫,毫秒級查詢、無外部依賴。
  • 緩存結果:Redis 緩存 24h,減少外部請求。
  • 併發控制:單一介面易被封禁,建議輪詢多個免費 API(ip-api.com、ipinfo.io、淘寶 IP 庫等)。
  • HTTPS:優先使用 HTTPS 介面防劫持。

現代替代方案

<?php
// 使用 Composer 套件 geoip2/geoip2 (需下載 .mmdb 資料庫)
$reader = new GeoIp2\Database\Reader('/path/GeoLite2-City.mmdb');
$record = $reader->city('8.8.8.8');
echo $record->country->name;       // United States
echo $record->city->name;          // Mountain View
echo $record->location->latitude;  // 37.4056
?>
copyright © 萬盛學電腦網 all rights reserved