这篇文章主要介绍了php基于新浪ip库获取ip详细地址的方法,涉及php正则、curl及编码转换相关操作技巧,需要的朋友可以参考下
具体如下:
<?php
class Tool{
/**
* 获取IP的归属地( 新浪IP库 )
*
* @param $ip String IP地址:112.65.102.16
* @return Array
*/
static public function getIpCity($ip)
{
$ip = preg_replace("/\s/","",preg_replace("/\r\n/","",$ip));
$link = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=".$ip."&t=".time();
$ipJson = self::httpCurl($link);
preg_match("/\"country\":\"(.*)\"/Uis",$ipJson, $match1);
preg_match("/\"province\":\"(.*)\"/Uis",$ipJson, $match2);
preg_match("/\"city\":\"(.*)\"/Uis",$ipJson, $match3);
return array(
'country'=>self::ucode2zh($match1[1]), // 国家
'province'=>self::ucode2zh($match2[1]), // 省
'city'=>self::ucode2zh($match3[1]) // 城市
);
}
/**
* Curl方式获取信息
*/
static public function httpCurl($url)
{
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_handle, CURLOPT_FAILONERROR,1);
$file_content = curl_exec($curl_handle);
curl_close($curl_handle);
return $file_content;
}
/**
* 将unicode编码转化为中文,转化失败返回原字符串
*
* @param $code String unicode编码
* @return String
*/
static public function ucode2zh($code)
{
$temp = explode('\u',$code);
$rslt = array();
array_shift($temp);
foreach($temp as $k => $v)
{
$v = hexdec($v);
$rslt[] = '' . $v . ';';
}
$r = implode('',$rslt);
return empty($r) ? $code : $r;
}
}立即学习“PHP免费学习笔记(深入)”;
获取IP地址类使用实例
<?php
$ipStr = Tool::getIpCity('112.65.102.16');
print_r($ipStr);立即学习“PHP免费学习笔记(深入)”;
返回结果
Array ( [country] => 中国 [province] => 上海 [city] => 上海 )
立即学习“PHP免费学习笔记(深入)”;
以上就是本文的全部内容,希望对大家的学习有所帮助。
相关推荐:
PHP strstr 函数判断字符串是否否存在的实例代码_php基础
PHP中基于ts与nts版本- vc6和vc9编译版本的区别详解_php基础
立即学习“PHP免费学习笔记(深入)”;
以上就是PHP基于新浪IP库实现获取IP详细地址的方法的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号