以ip.cn为例,根据IP地址在线查询省市区
<?php
$url='https://ip.cn/index.php?ip=8.8.8.8';
$data["country"] = 'unknown';
$data["region"] = 'unknown';
$data["city"] = 'unknown';
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT ,"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.113 Safari/537.36");
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
if (preg_match_all('%<p.*?>(.*?)</p>%si', $html, $matches)) {
$arr[0][] = $matches[1];
}
if ($arr[0][0][2] && strpos($arr[0][0][2], 'GeoIP') !== FALSE) {
$geoip = str_replace("GeoIP:", "", $arr[0][0][2]);
$geo_arr = explode(",", $geoip);
if (count($geo_arr) == 3) {
$data['country'] = trim($geo_arr[2]);
$data['region'] = trim($geo_arr[1]);
$data['city'] = trim($geo_arr[0]);
}
if (count($geo_arr) == 1) {
$data['country'] = trim($geo_arr[0]);
}
if (count($geo_arr) == 2) {
$data['country'] = trim($geo_arr[1]);
$data['region'] = trim($geo_arr[0]);
}
} else if ($arr[0][0][3] && strpos($arr[0][0][3], 'GeoIP') !== FALSE) { //过滤广告
$geoip = str_replace("GeoIP:", "", $arr[0][0][3]);
$geo_arr = explode(",",$geoip);
if (count($geo_arr) == 3) {
$data['country'] = trim($geo_arr[2]);
$data['region'] = trim($geo_arr[1]);
$data['city'] = trim($geo_arr[0]);
}
if (count($geo_arr) == 1) {
$data['country'] = trim($geo_arr[0]);
}
if (count($geo_arr) == 2) {
$data['country'] = trim($geo_arr[1]);
$data['region'] = trim($geo_arr[0]);
}
}
var_dump($data);
?>




