How to tell what is the user's preferred country/language?
is there any method to know the language of the 开发者_运维知识库user i think i have to know his Country first and detemine the language according to it
Any reason $_SERVER["HTTP_ACCEPT_LANGUAGE"]
won't work?
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
http://php.net/manual/en/reserved.variables.server.php
There are multiple approaches. However, I would recommend looking at Accept-Language first.
Only if that's absent should you consider falling back on the approach you've given. That's basically using geolocation to get the country or region, then guessing the language.
The latter is pretty flawed, because many countries and even regions are very multi-lingual.
First of all: There is a difference between the geographical location and the preferred language of a user and you can’t imply one information based on the knowledge of the other.
The geographical location of a user can be determined by geo-locating the IP address. And the best solution is to simply ask the user for his/her preferred language.
Because although the browser generally does send some language preferences along with the request (see Accept-Language header field and my answer on Detect Browser Language in PHP), these do not be the actual language preferences of the current user using the browser.
most browsers send their default locale with the request. you can retrieve this information through
$userLang = $_SERVER['HTTP_ACCEPT_LANGUAGE']
Check this out
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
Also
check this link
If $_SERVER['HTTP_ACCEPT_LANGUAGE']
is not helpful enough you can try this service
http://www.geoplugin.com/webservices/php
In case you need the full language names instead of the abbreviations (en, fr, etc.) try this basic function:
function parse_language( $languages = '' ) {
$translation = array( 'en' => 'English', 'fr' => 'French', 'es' => 'Spanish', 'de' => 'German', 'ja' => 'Japanese');
if( $languages == '' ) { //Default to HTTP accept language header
$languages = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
}
$languages = explode( ',', strtolower( $languages ) ); //Separate individual languages
foreach( $languages as &$language ) { //Filter out any county codes like -US
if( strpos( $language, '-' ) !== false ) {
list( $language, ) = explode( '-', $language, 2 );
}
}
//Find the intersections between the translation keys and the language values
return( array_values( array_intersect_key( $translation, array_combine( $languages, array_fill( 0, count( $languages ), '' ) ) ) ) );
}
//Sample usage
print_r( parse_language( 'en-US,de-GR,fr,es' ) );
If you need more language support, simple add more key/value pairs to the translation array.
You can use
http_negotiate_language($langs)
link to documentation
精彩评论