且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中检测客户端语言环境的最简单方法

更新时间:2022-10-16 07:41:57

不保证,但是大多数浏览器会提交一个接受语言HTTP标头,用于指定来自美国的en-us.不过,某些较旧的浏览器仅表示已启用.并非所有机器都正确设置以指示它们喜欢的语言环境.但这是一个很好的第一个猜测.

基于英语-英国的用户通常将其系统或用户区域设置设置为英语-英国,这在默认浏览器配置中应导致en-gb作为接受语言"标头. (很早以前说过en-uk,这是一个错字,很抱歉.)其他国家/地区也有en区域设置,例如en-za(南非),并且从理论上讲,也可以使用en-jp之类的组合.

但是,基于地理IP的猜测在首选语言/语言环境中不太可能是正确的. Google认为,基于IP地址地理位置的内容协商很有意义,当我在日本或韩国时,这确实让我很烦...

I would like to be able to detect what country a visitor is from on my website, using PHP.

Please note that I'm not trying to use this as a security measure or for anything important, just changing the spelling of some words (Americans seems to believe that the word "enrolment" has 2 Ls.... crazy yanks), and perhaps to give a default option in a "Select your country" list.

As such, using a Geolocation database is a tad over-the-top and I really don't want to muck about with installing new PHP libraries just for this, so what's the easiest/simplest way to find what country a visitor is from?

Not guaranteed, but most browsers submit an Accept-Language HTTP header that specifies en-us if they're from the US. Some older browsers only said they are en, though. And not all machines are set up correctly to indicate which locale they prefer. But it's a good first guess.

English-UK based-users usually set their system or user locale to English-UK, which in default browser configurations should result in en-gb as the Accept Language header. (An earlier version of this said en-uk; that was a typo, sorry.) Other countries also have en locales, such as en-za (south africa), and, primarily theoretically, combinations like en-jp are also possible.

Geo-IP based guesses will less likely be correct on the preferred language/locale, however. Google thinks that content-negotiation based on IP address geolocation makes sense, which really annoys me when I'm in Japan or Korea...