/ 網站開發

2023年02月17日 145

geoPlugin 透過IP取得國家/地區


當需要透過IP Address去抓取國別/地區的相關對應資料時
Geoplugin API 實在太厲害了,只需要帶入IP就可以抓到國別/地區與其他相關資料
但通常應用上,只需要抓地區名稱或代碼就很好應用了
使用方法也很簡單,透過 http://www.geoplugin.net/json.gp?ip=xxx.xxx.xxx.xxx
只需要在 xxx.xxx.xxx.xxx 替換或抓取為IP即可爬到對應的地區資料
以下為實作上透過 file_get_contents 處理的 function

<?php
# 透過IP取得國家/地區
	function getGeoInfo() {
		$result = NULL;

		if (filter_var($client, FILTER_VALIDATE_IP)) {
	        $ipAddress = $_SERVER['HTTP_CLIENT_IP'];
	    }elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
	        $ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
	    }else{
	        $ipAddress = $_SERVER['REMOTE_ADDR'];
	    }

	    $API_URL = 'http://www.geoplugin.net/json.gp?ip='.$ipAddress;
	    $array = @json_decode(file_get_contents($API_URL), true);
	    if (!empty($array)) {
	    	$result['countryCode'] = $array['geoplugin_countryCode'];
	    	$result['countryName'] = $array['geoplugin_countryName'];
	    	$result['city'] = $array['geoplugin_city'];
	    }

	    return $result;
	}

因為產生的結果為array格式,若需要模擬可轉為JSON格式,參考如下:

<?php
   $jsonData = $this->customize->getGeoInfo();
   echo json_encode($jsonData);

抓取結果的JSON為:

{
countryCode: "TW",
countryName: "Taiwan",
city: "Chushui"
}

如此一來,把需要的資料帶回資料庫紀錄,就可以做國別分析囉!

參考連結:https://www.geoplugin.com/

標籤: #PHP , #API