I have developed a website www.tenxian.com.
It has three language versions, English, Japanese and Chinese. How can I write an effective PHP program which can automatically choose a language version based on the IP address of the visitor?
If I use "if-else", the code would be much complicated; If I use switch-case, how to write it since the data which should be dealt with are IP ranges, not particular numbers. Besides, I don't know these IP ranges
What is the easiest way to do it?
Please, PLEASE, do not make the mistake of thinking that IP == language. Look at the browsers accept-language header first, then the browser identification string which might contain the OS language, and only then take the IP into account. In almost 100% of all cases the browser accept-language header will be present and sufficient.
And always give the user the choice to switch to another language.
Just apart from the simple case of a foreigner abroad, how do you determine the language for Belgium, where they speak French, Dutch and German? (Maybe that doesn't apply to your case, but just philosophically. :)).
Check out GeoPlugin:
http://www.geoplugin.com/webservices/php
Yes please don't do it... Google does this and dreaking annoying.. I always get the thai version instead the english one from my browser.
Use the http headers from the browser.
<?php
$ln = split(",",$_SERVER["HTTP_ACCEPT_LANGUAGE"]);
print_r($ln[0]);
?>
Perhaps this will help: www.countryipblocks.net
You'd probably want to use some form of IP geocoding database (example).
Assuming you can convert IP ranges to one of your language choices, you could do this (all replies above): have all your messages in the applications stored in an associative array of this form.
$MESSAGES[$USER_LANGUAGE][$msgId]
where $USER_LANGUAGE can be chinese, japanese, or english (or any other equivalent enum). $msgId can be things like "login.successful", "login.fail" etc. Where ever you display messages to the user do not display hardcoded strings, make a reference to the variable using the $msgId.
You can access it as a global variable OR you can create a function that takes in the $msgId as a parameter and returns the message, $USER_LANGUAGE can be a global variable as well (which is set the first time the user comes in).
take a look at the maxmind geoip module for PHP (http://www.maxmind.com/app/php), as for your data structure perhaps key it to the ISO-3166-1 country code which apache_note("GEOIP_COUNTRY_CODE"); returns.
Related
I have a multilanguage site and I would like PHP to automatically set the language depending on the location from where you enter the site.
I tried a couple of ways.
localeconv() is not returning local language at all,
nl_langinfo() was also not helpful at all,
mb_language() returns not the language I was looking for,
$_SERVER['HTTP_ACCEPT_LANGUAGE'] this returned me a couple of languages instead of just one.
setlocale(LC_ALL, 0) returned C for some reason.
But I failed to get the correct info every time.
I guess that setlocale(LC_ALL, 0) is the best solution, but I don't know what the returning C means and I don't know what to expect from different languages.
I looked for a solution on many different sites (including SO) and found the solutions I mentioned earlier. Unfortuately none of them did what I was looking for.
I use $language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); to get the first (= preferred) entry of the language array, reduced to 2 characters, for example "en" or "de"
Another approach without substr: locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE'])
Short answer: Language and location are very different things. You shouldn't set the language based on the location.
Why?
Many countries have multiple languages. Additionally, if you are English and you log onto your favourite website while you are on holiday in Japan, you don't want to see it in Japanese.
As Johannes mentioned, better to use the browser's language ($_SERVER['HTTP_ACCEPT_LANGUAGE']) if you want to make that decision automatically.
I'm looking for a way to get a user default language by the country. For example I have windows in english but still I would like to get my country 2 letter language ("cs")
You can see an example of what I want, In the source code of http://search.conduit.com/ using (Autocompleteplus) as well. This is what I see:
window.language = "en-us";
window.countryCode = "cz";
window.suggestBaseUrl = "http://api.autocompleteplus.com/?q=UCM_SEARCH_TERM&l=cs&c=cz&callback=acp_new";
You can see the api url has inside "l=cs&c=cz" how did they get this information? I would like to have the same thing I use the same autocompleteplus method just need a way to generate the l=(user true langague)&c=(country code) and performance is important as well. It's autosuggestions for my website search.
This is Ed from AutoComplete+. Getting the user country is typically done when using our API through server side implementations. There are however some open APIs that can assist you. Regardless, you can use our autocomplete feed without the user country. Feel free to contact us directly for further info at http://www.autocompleteplus.com
Thanks,
--ed
I have PHP-MySQL Website with admin panel. I can enter data from admin panel and they display on user side web pages. Now, I want that I should be able to insert text data in English language from admin panel and they should display in 3 different languages at user side.
At user side, I want to give options for visitors to select language preference and user sides pages should display in that selected language. Right now I am completely unaware for what programming related changes I will need to make on user sides pages to make this possible.
I have searched and read some articles on internet but frankly could not find solution that will work for my case. So please help me.
Following things are used / set in my working environment.
Windows Server 2003
PHP 5.2.17
MySQL 5.0.51a (UTF-8 Unicode (utf8))
XHTML 1.0 Transitional
meta charset=iso-8859-1
Thank you in advance,
KRA
Assuming you have all your language variables and/or html views separated out into some sort of structure, you could always just use a cookie.
Have your site check for the presence of said cookie and if it doesn't exist, then have the site revert to the default language, otherwise adjust the language accordingly.
Ex:
Have a form with dropdown values for each language and when it is submitted, set the language cookie variable:
setcookie('userLanguage',$language_value,strtotime("+1 year"));
The first parameter is the name of the cookie variable, the second is the value (in this case, the user's language selection, and the third is the expiry date of the cookie (I made it one year, but you can set it to whatever you like).
The next step really depends on how your site is setup, but I'll assume that you have your language text in a db or handled in some intelligent way. Either way, you need to retrieve the cookie:
if ($_COOKIE['userLanguage'] <> '')
// Do some language stuff here based on the value of $_COOKIE['userLanguage']
else
// Do some stuff here for default language
That's about it. There are a lot of different ways to handle the actual language conversion, but the act of getting the user's preference and remembering it is pretty much as basic as that.
Assuming that you want the translations performed on the server side (PHP) you can use file_get_contents to fetch data from Google Translate API. Then you need to parse the response and get translated text. You need to get API KEY to access the Translate service.
<?php
$string = 'Hello World';
$source_lang = 'en';
$target_lang = 'zh-CN'
header ( "Content-Type: text/html;charset=utf-8" );
$data = file_get_contents ( 'https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&q='.urlencode($string).'&source='.$source_lang.'&target='.$target_lang );
$data = json_decode ( $data );
$translated = $data->data->translations->[0]->translatedText;
echo $translated;
?>
Server responses are JSON objects with that structure:
{
"data": {
"translations": [
{
"translatedText": "Hallo Welt",
"detectedSourceLanguage": "en"
}
]
}
}
More info about basic concept is avaliable on:
http://baris.aydinoglu.info/coding/google-translate-api-in-php.
Documentation of Google Translate API queries:
http://code.google.com/apis/language/translate/v2/using_rest.html
You may use this and save the relevant data to your database. You may have separate columns for each language in your database table. Once the text / data is entered by the admin, you have to convert them using the solution and save them to relevant columns on the SAME row. The user may be given data from the relevant column according to their language selection.
Well this depends alot on how you store your textual data. If you have it in a db (mysql) then i suggest that you have a collumn that stands for the language. Then you could have either a session variable or a specific url or something else that gives you some indication of which language the user is requesting.
What you need is some way to figure out what kind of language your user wants, after that it's quite easy.
Have you tried anything yet?
Use language Files in your website.
For example,
For english -en.php
For French -fr.php
This files will have variables that will be used in front User end.User can select any language and on selecting, your code will load the following language
In your case, you are using database, so you can have this thing in your tables instead of Database
so your Front files will consist of variables instead of Text and this variables will be replace by language variables(Either from database or from files, its your choice) when user select a language
And yes, you need to put a default language.
Use following links to implement :-
http://scriptdigital.com/divers/phplocalization.html
http://www.mind-it.info/2010/02/22/a-simple-approach-to-localization-in-php/
http://code.google.com/p/slsphp/
Use this method.
Its working for me.
Switching languages on a website with PHP
I've done it in oyutrade.com
I am working on a website and the requirement is to make it in two languages i.e. icelandic and english.
just like facebook and other google, if a user selects a language, then the site is translated in that language.
I am not allowed to use google translator.
Any other way to do this in Php
Thanks in advance
Well, I never did it, but i did think about it :), for me i have to do something like this from scratch,
First, do not echo your String that will be displayed to your clients hardcoded, create a dictionary, this dictionary can be in any format, be it php file, xml file, json. You can also extend the functionality by adding Database in it. The main idea is to create a dictionary having all your messages that will be displayed to the user in all the languages you want to display it
consider if you do it using normal PHP FIle, use OOP built class say known as Message, then as attribute to the class add the several languages that you have to use and also some setters and getters
e.g.
Message
{
english;
french;
.....
}
then in PHP, when you echo your messages, try to get the language you want to use, and then
do something like this
echo message.getEnglishMessage();
Look, I've been very generic, now decide on the type of file that you'll use and build the dictionary
Hopes it helps :-)
I use an es.php (spanish not sure what icelandic is) and build all of the mod_rewrite off that. You treat it exactly same as you would if it were the index.php for english. For inputing data into the database have a column for language. All of your queries that call data will then have the language as a condition.
The "gettext" is the way you can go with but if you and your client are in nice understanding ask him to provide the data in language other than english as well and then in DB table there will be a column 'language' in which 'ic' or 'en' flag will be the data, and during fetching the data anywhere, according to language your sql query will contain the language as a where condition with desired flag as its value.
Currently I'm writing a short survey (html form) using php, mysql and jquery. I want the user to select their country from a drop-down list and then get the right currency (server side) so later on I can ask things referring to the right currency.
I really don't got a clear view on how to achieve this. I know I can find an up to date country list from: http://www.iso.org/iso/country_codes/iso_3166_code_lists.htm
I could make into a php array but then?
http://snipplr.com/view/36437/php-country-code--to-html-currency-symbol-list/
Seems nice code, but I like to use something that is up to date.
Its no problem for me to use a mysql database, but it is a problem to install plug-ins/expansions (hosting won't allow it).
Does somebody knows a good (and maybe easy) way to achieve this?
You can use CURL or file_get_contents() to read the content from the URL and is always updated.
Not answering your question, but:
As of PHP5.3 the intl became a default. It contains NumberFormatter::formatCurrency() that does what your linked country_currency() is trying to do - only properly. If PHP5.3 is a viable minimum requirement (seeing that 5.2 is deprecated and not supported anymore) - use the intl functions.
With Locale::acceptFromHttp() you can check the browser's request headers to preselect the best matching locale.
Your ISO CountryCode list should still be helpful for a manual <select> on a certain level. But keep in mind that it's not quite accurate: Germany translates to de, which may not be specific enough seeing de_AT, de_CH, de_DE. Each of them may present Currency differently. €1,123.23, 1 123,23 €, and so on. You'll still need to know which currency you're processing, though. So you need the list of ISO country codes AND the map of countrycode to currency.
PHP Intl's NumberFormatter accepts English as a language for any country. So just use en_ plus your country code.
echo (new NumberFormatter('en_DE', NumberFormatter::CURRENCY))
->getTextAttribute(NumberFormatter::CURRENCY_CODE); // EUR
echo (new NumberFormatter('en_RS', NumberFormatter::CURRENCY))
->getTextAttribute(NumberFormatter::CURRENCY_CODE); // RSD