Detect Browser Language in PHP

后端 未结 13 1446
孤城傲影
孤城傲影 2020-11-22 09:16

I use the following PHP script as index for my website.

This script should include a specific page depending on the browser\'s language (automatically detected).

13条回答
  •  礼貌的吻别
    2020-11-22 09:50

    The official way to handle this is using the PECL HTTP library. Unlike some answers here, this correctly handles the language priorities (q-values), partial language matches and will return the closest match, or when there are no matches it falls back to the first language in your array.

    PECL HTTP:
    http://pecl.php.net/package/pecl_http

    How to use:
    http://php.net/manual/fa/function.http-negotiate-language.php

    $supportedLanguages = [
        'en-US', // first one is the default/fallback
        'fr',
        'fr-FR',
        'de',
        'de-DE',
        'de-AT',
        'de-CH',
    ];
    
    // Returns the negotiated language 
    // or the default language (i.e. first array entry) if none match.
    $language = http_negotiate_language($supportedLanguages, $result);
    

提交回复
热议问题