作者:空白画叶子 | 来源:互联网 | 2018-07-16 02:59
PHP获取IP的地理位置都是使用相关函数+正则表达式来获取指定网页中的信息了,下面我整理几个常用的接口与获取方法,有需要了解的朋友可进入参考。
用php file_get_contents 获取ip地址后如何获取地理位置,看下下面代码:
使用file_get_contents和fopen必须空间开启allow_url_fopen。方法:编辑php.ini,设置allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。
例子
代码如下 |
|
function get_ip_place()
{
$ip=file_get_contents("http://fw.qq.com/ipaddress");
$ip=str_replace('"',' ',$ip);
$ip2=explode("(",$ip);
$a=substr($ip2[1],0,-2);
$b=explode(",",$a);
return $b;
}
|
还有一种办法:
来看看
代码如下 |
|
function get_ip_arr()
{
$ip=file_get_contents("http://fw.qq.com/ipaddress");
preg_match_all("/"(.*)"/",$ip,$arr);
return $arr;
}
|
返回来的是个数组,里面可以任意去取地区或者是ip
/使用curl:
使用curl必须空间开启curl。方法:windows下修改php.ini,将extension=php_curl.dll前面的分号去掉,而 且需要拷贝ssleay32.dll和libeay32.dll到C:/WINDOWS/system32下;Linux下要安装curl扩展
例子
代码如下 |
|
function getIPLoc($queryIP){
$url = 'http://ip.qq.com/cgi-bin/searchip?searchip1='.$queryIP;
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_ENCODING ,'gb2312');
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
$result = curl_exec($ch);
$result = mb_convert_encoding($result, "utf-8", "gb2312"); // 编码转换,否则乱码
curl_close($ch);
preg_match("@(.*) @iU",$result,$ipArray);
$loc = $ipArray[1];
return $loc;
}
|