Internationalization: preferedLanguage S

I’m working on a web site providing internationalization.

the CHttpRequest::preferredLanguage is not very helpfull in this case.

it assumes that a end-user can choose only one language, and it’s false, a user can choose many prefered many languages.

example :

  • my site is in ‘fr’, ‘ko’, ‘it’ ( default fr)

the user choosed ‘en’, ‘ko’ as prefered languageS.

if I use CHttpRequest::preferredLanguage, for this user, I will show him our web site in ‘fr’ :

CHttpRequest::preferredLanguage return ‘en’ , knowing we dont have ‘en’, we use the default lauguage of the web site.

If Yii provided a CHttpRequest::preferredLanguages I could show the website in ‘ko’

It’s what we do actually… but in analyzing by our self the request…

the property name ‘preferredLanguage’ may be confused for a developper… in fact you should call it ‘firstPreferredLanguage’.

In fact if you want to work with internationalization, you should never use CHttpRequest::preferredLanguage !

so… it should be nice to have a new property on CHttpRequest :

  • preferredLanguages (with an s at the end) : array of preferred languages

Do you know how it determines the preferred language? Please see http://www.yiiframework.com/doc/api/1.1/CHttpRequest#getPreferredLanguage-detail

If you have any other way of determining the language then lets here it, Other wise we can’t just guess the user preferred languages, As in plural.

Knowing that im a newbie in Yii , its maybe not the ‘perfect’ method.

first, extending ChttpRequest

class EHttpRequest extends CHttpRequest

{

public function getPreferredLanguages()


    {


	 if(!isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))


		{


	     return array();


		}


	 $browserLanguages = explode( ',', $_SERVER['HTTP_ACCEPT_LANGUAGE'] );


	 for ( $i = 0; $i < count($browserLanguages); $i++ )


		{


		$language = explode( ';', $browserLanguages[$i] );


		 $browserLanguages[$i] = $language[0];


		}


	 return $browserLanguages;


}

}

then in my code,

$preferedLanguages = Yii::app()->getRequest()->getPreferredLanguages();

for example on my firebox

$preferredLanguages -> Array ( [0] => en-us [1] => en [2] => ar )

on my chrome

$preferredLanguages -> Array ( [0] => fr-FR [1] => fr [2] => en-US [3] => en )

if you don’t want the country code ( last 2 caracters, like in en_uk, fr_fr…)

replace in the function

		 $browserLanguages[$i] = substr($language[0],0,2);


		}


	 return array_values(array_unique($browserLanguages));

in this case

n my firebox

$preferredLanguages -> Array ( [0] => en [1] => ar )

on my chrome

$preferredLanguages -> Array ( [0] => fr [1] => en )