Posted By

Hexahow on 02/08/13


Tagged

list country ip geolocationtrace


Versions (?)

Country list based on browser's language


 / Published in: PHP
 

URL: http://www.geolocation.com

The following codes populate the country list into dropdown box based on browser's languages. The country information is getting from geolocation.com

  1. <?php
  2. ////////////////////////////////////////////////////////////////////////////////////////////////
  3. //The following codes populate the country list into dropdown box based on browser's languages.
  4. //The country information is getting from geolocation.com,
  5. //free license with attribution: The geolocation data is provided by http://www.geolocation.com
  6.  
  7. //Get the languages
  8. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  9. echo '<p>Browser Languages: ' . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . '</p>';
  10. echo '<p style="margin:0px; padding:0px;">Country List <span style="font-size:9pt; display:block;">The geolocation data is provided by <a href="http://www.geolocation.com">http://www.geolocation.com</a></span></p>';
  11.  
  12. ////////////////////////////
  13. //Get the browser languages
  14. if(preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_matches)){
  15. $langs = array_combine($lang_matches[1], $lang_matches[4]);
  16. foreach ($langs as $lang => $val)
  17. if ($val === '') $langs[$lang] = 1;
  18.  
  19. arsort($langs, SORT_NUMERIC);
  20. }
  21.  
  22. //Default to english
  23. $language = 'en-us';
  24. foreach ($langs as $lang => $val){
  25. $language = $lang;
  26. break;
  27. }
  28.  
  29. //////////////////////
  30. //Load the Country File
  31. //Notes:
  32. //Download the CSV file from http://www.geolocation.com
  33. //Rename the CSV to country-en-us.csv (for english version),
  34. //country-zh-cn.csv (for chinese simplified version),
  35. //country-zh-tw.csv (for chinese traditional version)
  36. //and save in the same folder as the php code resided.
  37. echo '<select>';
  38. $countries = file_get_contents("country-$language.csv");
  39. if (preg_match_all('/"(.*?)","(.*?)","(.*?)","(.*?)"/', $countries, $matches)){
  40. for($nIdx=1; $nIdx < count($matches[1]); $nIdx++){
  41. $alpha2_code = $matches[1][$nIdx];
  42. $country_name = $matches[4][$nIdx];
  43. //echo $alpha2_code . ',' . $country_name . '<br/>';
  44. echo '<option value=' . $alpha2_code . '">' . $country_name . '</option>';
  45. }
  46. }
  47. echo '</select>';
  48.  
  49. }
  50. else
  51. echo 'Unable to locate browser languages';
  52. ?>

Report this snippet  

You need to login to post a comment.