Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need an example on how to get preferred language from Accept-Language request header

Tags:

java

c#

.net

php

I need a code example or library which would parse Accept-Language header and return me preferred language. RFC2616 states that:

The Accept-Language request-header field is similar to Accept, but restricts the set of natural languages that are preferred as a response to the request. Language tags are defined in section 3.10.

   Accept-Language = "Accept-Language" ":"
                     1#( language-range [ ";" "q" "=" qvalue ] )
   language-range  = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" ) 

Each language-range MAY be given an associated quality value which represents an estimate of the user's preference for the languages specified by that range. The quality value defaults to "q=1".

Further reading shows that there are too many "optional", "should", "may" and other turns of speech that prevent me from reinventing the wheel - all I want to know is what language user prefers, any browser answers this question billion times a day.

Any code snippet in any language (except Lisp and Assembler please) would be helpful.

Many thanks in advance!

like image 587
andbi Avatar asked Mar 29 '12 14:03

andbi


People also ask

How do I accept a language header?

The Accept-Language request HTTP header indicates the natural language and locale that the client prefers. The server uses content negotiation to select one of the proposals and informs the client of the choice with the Content-Language response header.

How do I change my accept-language?

The user can change the Accept-Language header sent by the browser using the browser's preference settings. E.g., in Chrome, go to “Settings”, click on “Show advanced settings...”, scroll down to “Languages”, click on “Language and input settings...”, and then add languages and drag to order them.

How do I set the language header in Chrome?

Checking your Accept-Language headersRun the Internationalization Checker on any page, then in the Information panel, look under Request Headers > Accept-Language .

How do I create a custom request header?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.


2 Answers

Solution:

namespace ConsoleApplication
{
    using System;
    using System.Linq;
    using System.Net.Http.Headers;

    class Program
    {
        static void Main(string[] args)
        {
            string header = "en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2";
            var languages = header.Split(',')
                .Select(StringWithQualityHeaderValue.Parse)
                .OrderByDescending(s => s.Quality.GetValueOrDefault(1));
        }
    }
}

Result:

enter image description here

like image 101
Zygimantas Avatar answered Oct 04 '22 02:10

Zygimantas


Try this, its in PHP but using the same regex i'm sure its adaptable to any language :

$langs = array(); // used to store values

if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    // break up string into pieces (languages and q factors)
    preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

    if (count($lang_parse[1])) {
        // create a list like "en" => 0.8
        $langs = array_combine($lang_parse[1], $lang_parse[4]);

        // set default to 1 for any without q factor
        foreach ($langs as $lang => $val) {
            if ($val === '') $langs[$lang] = 1;
        }

        // sort list based on value 
        arsort($langs, SORT_NUMERIC);
    }
}

produces a sorted array with preferred language first :

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

From example ACCEPT_LANGUAGE header : en-ca,en;q=0.8,en-us;q=0.6,de-de;q=0.4,de;q=0.2

Working example here

like image 38
Manse Avatar answered Oct 04 '22 02:10

Manse