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 => 中國 北京 百度
<?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
?>