溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在PHP中利用新浪IP庫獲取IP詳細地址

發(fā)布時間:2021-02-05 16:15:29 來源:億速云 閱讀:191 作者:Leah 欄目:開發(fā)技術

這篇文章將為大家詳細講解有關怎么在PHP中利用新浪IP庫獲取IP詳細地址,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。

具體如下:

<?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, $match2);
    preg_match("/\"province\":\"(.*)\"/Uis",$ipJson, $match3);
    preg_match("/\"city\":\"(.*)\"/Uis",$ipJson, $match4);
    return array(
      'country'=>self::ucode2zh($match2[1]), // 國家
      'province'=>self::ucode2zh($match3[1]), // 省
      'city'=>self::ucode2zh($match4[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;
  }
}

獲取IP地址類使用實例

<?php
$ipStr = Tool::getIpCity('112.65.102.16');
print_r($ipStr);

返回結果

Array ( [country] => 中國 [province] => 上海 [city] => 上海 )

關于怎么在PHP中利用新浪IP庫獲取IP詳細地址就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI