How to get the language value from $_SERVER['HTTP_ACCEPT_LANGUAGE'] using PHP?

后端 未结 4 1918
野性不改
野性不改 2020-12-08 11:19

When I use Firefox to test this block of code, I get en-us,en;

4条回答
  •  鱼传尺愫
    2020-12-08 12:20

    Yes, the value of $_SERVER['HTTP_ACCEPT_LANGUAGE'] is a string -- see $_SERVER.

    Its content is sent by the browser -- which explains why you get different results depending on the browser you are using : most likely, your Firefox is configured to request pages in english (high priority) or japanese (low priority), while your IE is configured to request pages in chinese.

    This is because that HTTP header can contain :

    • a list of languages
    • optionnaly, with region codes
    • with associated priorities.

    The idea being that the server should respond, using the language that suits "the best" what's requested by the user.


    About parsing that header, this blog-post might be a interesting read : Parse Accept-Language to detect a user's language

    There is a portion of code proposed to parse that HTTP header -- and it generates an array that looks like this (quoting) :

    Array
    (
        [en-ca] => 1
        [en] => 0.8
        [en-us] => 0.6
        [de-de] => 0.4
        [de] => 0.2
    )
    

    Which is an array of languages, sorted by priority, in descending order -- which is probably what you want.

提交回复
热议问题