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("@<span>(.*)</span></p>@iU",$result,$ipArray);
- $loc = $ipArray[1];
- return $loc;
- }
新聞熱點
疑難解答