peterkahl/language-detector

Chooses language most likely to be understood by site's visitor.

v4.0.1 2018-03-22 14:41 UTC

README

Determines website visitor's most likely language. Works by parsing HTTP header Accept Language, or, when the header is not sent, other clues are used:

  • The server may know the client's locale code. Language is then determined from locale.
  • The server may know the client's country code (from IP address). Language is then determined from country code.

Dependency

Package peterkahl/country-to-locale is a required dependency.

Usage

use peterkahl\languageDetector\languageDetector;

# For testing purposes, we set the header. Otherwise to be omitted.
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'zh-CN,zh;q=0.5,en;q=0.25';

$langObj = new languageDetector;
$langObj->languageDefault = 'en-gb';
$langObj->languageMap     = array(
                              'zh-hk'    => 'zh-hk',
                              'zh-mo'    => 'zh-hk',
                              'zh-tw'    => 'zh-hk',
                              'zh-hant*' => 'zh-hk',
                              'zh-yue*'  => 'zh-hk',
                              'zh-cn'    => 'zh-cn',
                              'zh-sg'    => 'zh-cn',
                              'zh-my'    => 'zh-cn',
                              'zh-hans*' => 'zh-cn',
                              'zh'       => 'zh-cn',
                              'ja*'      => 'ja-jp',
                              'sk*'      => 'sk-sk',
                              'cs*'      => 'cs-cz',
                              'it*'      => 'it-it',
                              'nl*'      => 'nl-nl',
                              'fr*'      => 'fr-fr',
                              'ru*'      => 'ru-ru',
                              'es*'      => 'es-es',
                              'pt*'      => 'pt-pt',
                              'de*'      => 'de-de',
                              'en*'      => 'en-gb',
                            );

$langObj->countryCode     = 'DE'; # Value provided by GeoIP detection of your server
$langObj->anonymousProxy  = 'no'; # Value provided by GeoIP detection of your server
$langObj->detect();

echo $langObj->getLanguage(); # zh-cn
echo $langObj->getMethod();   # accept-language