基于浏览器语言的国家/地区列表

Posted

tags:

篇首语:本文由小常识网(cha138.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*qs*=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. ?>

以上是关于基于浏览器语言的国家/地区列表的主要内容,如果未能解决你的问题,请参考以下文章

如何在 mern 堆栈中获取注册表单的国家/地区列表?

根据列中的国家/地区名称插入国家/地区官方语言

Paypal 托管语言错误。 Paypal Express 按钮基于“国家/地区”而不是“lc”

每个国家/地区的 CultureInfo 名称

PHP PHP国家代码到国家/地区名称列表

在Java Servlet中自动为用户选择国家/地区和语言