關於IP對應國家或相關資料的服務

2015-11-06

如果透過IP位址我們想要知道該位址的所在地或是座標等資料,我們除了自己建立資料庫以外,也可以透過網路服務來進行

取得IP的相關資料:


//for php developer
$ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
echo $details->city; // -> "Mountain View"
 

如果你是前端的開發者,可以用以下javascript的方式

 
$.get("http://ipinfo.io", function(response) {
       console.log(response.city);
}, "jsonp");
 

此外,取得後有些資料並不一定會以完成的名稱來顯示,資料集所提供的資料, 可能會以代碼的方式來呈現,如透過上方取地的country值會以ISO2 country code的形式來顯示(TW, US, AU...),這時候我們仍可透過API的服務來進行轉換


$names = json_decode(file_get_contents("http://country.io/names.json"), true);
echo $names['US']; // => United States
echo $names['NL']; // => Netherlands
 

假如您有想要自行維護這樣的轉換,如轉換為其他語系等等,除了透過網路提供的各式API來實現之外,也可自行建立函式來處理,請參閱下方連結來了解撰寫方式:

http://stackoverflow.com/a/31775727

 

 

Contact

Github

Codepen

歡迎參觀我的賣場
© 2013 Copyright Digishot Web | Design Tools
Visitors【622486】
digishot webdesign studio