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.
Related
SHORT DESCRIPTION
It will be Lithuanian - English website (only 2 languages).
This will be jobs listing website, so content shouldn't be translated. If employer provided job in English so this should be in English even if Lithuanian language is selected. There should be translated only field names, buttons & error messages.
QUESTION IN SHORT
What is better way to have single file index.php for both languages or create separate files for LT and EN languages?
1st WAY
So I can make It in few ways, for example:
www.mysite.com/jobs -- default Lithuanian language
www.mysite.com/en/jobs -- English language
So in this case I need to have 2 duplicate websites (just translated) Lithuanian stored in root/ folder and English stored in root/en/ folder? So If I change something in Lithuanian website I need to make exact changes in English website?
It not looks like good practice to write code twice.
2nd WAY
Create variable something like $lang = "en";, store all field names in database in way like this:
Id FieldName_lt FieldName_en
1 Vardas First Name
2 Pavardė Last Name
3 El. paštas E-mail
And select from database via PHP like SELECT FieldName_ . $lang FROM table..., but It could be SQL Injected If I'll use variable in SQL query.
3rd WAY
Maybe It's better way to store field names in arrays (there will be maybe 150+ fields)?
If I'll go for 2nd or 3rd way, should I save language choice in cookies? So in this way website url always will be like below?
www.mysite.com/jobs.php?lang=en
www.mysite.com/jobs.php?lang=lt
Maybe there is another way to make It, without showing language choice in address bar at all? Or It's bad practice to hide language choice form address bar?
ADDITIONAL
In HTML form I'm using data validation in following:
<input type="text" id="first-name" placeholder="" required
data-validation="length alphanumeric"
data-validation-length="3-12"
data-validation-error-msg="User name has to be an alphanumeric value (3-12 chars)"/>
So how about error message translation?
The same as database approach you can use static file for each language and translation.
en.php
return [
"somekey" => "English Translation"
];
lt.php
return [
"somekey" => "Lithunian Translation"
];
You can then mod rewrite to get language from url if you want some directory structure, or simple query parameter or cookies (as specified by others). If you are using any any RESTfull service it is also possible to set it in HTTP header. Many frameworks also there to help you parse data from url out of the box.
$langCode is language code fetched from Query PAram, url path, header or cookie
you can also use http://php.net/file_exists to check if translation file is available or not before you use require_once to pull the translation resource.
Once you get the language code you can just use
$stringResource = require_once "lang/{$langCode}.php";
Then you can fetch all the resource by its key from $stringResource.
<?php $stringResource = require_once "lang/{$langCode}.php"; ;?>
<input type="text" id="first-name" placeholder="" required
data-validation="length alphanumeric"
data-validation-length="3-12"
data-validation-error-msg="<?php echo $stringResource['somekey'] ;?>"/>
You can just edit the translation in editor. wont need to connect to database and as it is just assoc array. it would be way faster.
Query:
www.mysite.com/jobs.php?lang=en
as already mentioned it will be ignored in term of SEO. Query parameters are ignored by crawlers.
URL Path
www.mysite.com/en/jobs.php
here you need to do mod rewrite http://httpd.apache.org/docs/2.0/misc/rewriteguide.html which is basically just catch url and fetch out the en part and rewrite to something like www.mysite.com/jobs.php?lang=en
Both data can be get from $_GET['lang']. but url path will have benefit on SEO.
Cookies
Will not be shown in address bar. but that also means if the link is shared to another user they will not see the language of origin they will see default language.
https://support.google.com/webmasters/answer/182192?hl=en#1 as per google doc. i believe it would be nice to do it using url path.
I think the approach with the Database is fine. Whenever you want to change the translation for something you will just have to edit the table entry. You can write a class which doeas the translation for you, so you only have to pass the language-id and the language.
How to save the language/ how to display it: It depends on how it is meant to be used. If it is likely people often share a link to your site, you could inclue the language in the url, e.g. as a GET paramater. If it should "just" stay the same for the user who visited the site, cookies are a nice approach.
Using a cookie to store the language preference is an option but might cause some issues for SEO and this will be relevant for a job site.
Without using cookies you can either put the language in the directory path as you suggested. You don't need to have 2 separate websites then, you can use url rewriting to change a part of the path into a query parameter (for apache use mod_rewrite).
Using just a query param, just as your second suggestion will work too but looks less nice.
Make sure you offer your users a option to switch language, for example using flag icons or just text links.
As I've started building a project, there will be quite a few entries in the .po translation file. I use Poedit to build these.
My question is, what is the best practice for entries within this file? I was thinking, instead of referencing entries such as:
echo _('This is an entry.');
I was thinking of organizing them like:
echo _('error_pwd');
echo _('error_user_taken');
Which, once ran through the translation file, would output something like:
Password incorrect. Please try again.
Username is already taken. Please try another.
So, all my translations can be organized by type, such as error_, msg_, status_, tip_, etc.
Has anyone seen it done this way, or have any suggestions on a more organized method?
In fact it doesn't matter!
It's just up to you.
However, I advise you do not split translations in sections.
No there's any benefit in doing so. Actually, the most projects use the one file approach for all msgid entries.
Like django, see.
Of course, If you still want split translation by sections, might you want take a look on Domains:
From PHP doc:
This function (textdomain()) sets the domain to search within when calls are made to
gettext(), usually the named after an application.
Also, as earlier said, the advantage when using msgid as a real phrase ou word (instead underline or dotted notation key) is that it stays as default message if no there's a translation for entry.
And here goes some helpful links:
Django Porject - i18n, Definition
PHP textdomain function
What is bindtextdomain, textdomain in gettext?
How to determine which catalog to be used
This is a standard approach for other framework, e.g. Symfony/Laravel:
trans('error.validation');
But it has a downfall, if you forget to translate one phrase on your site it will appear like the keyword 'error.validation'
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 need to translate my site in multiple languages. i was thinking to use a database called language and put the translation there.
database : translation
tables: language
column: id, english, french, german, italian, spanish
or i was thinking about a php solution like:
english.php
french.php
german.php
italian.php
spanish.php
so you simply include the file you need.
now, i can see pros and cons for both, what i want to know is what is consider the standard in the industry to do something like this?
You can use gettext, this function is proposed for this feature, not a "standard" but fast enough.
The second options in the use of a PHP file with a big array (really big, for each string), this is the most common solution.
To the database content (the big problem here, don't forget), if all your content must have the translation, one column for each language, otherwise use a flag of language for each line on database.
There is no industry standard. I have seen (and implemented) solutions using flat files, XML, PHP code, a database, and gettext files to store the localized strings. It's a matter of what is more suitable for you.
My go-to method for PHP is simply files containing arrays of strings, for example
en.php
return array (
'How are you?' => 'How are you?',
'Goodbye' => 'Goodbye',
);
de.php
return array (
'How are you?' => 'Wie gehts?',
'Goodbye' => 'Auf wiedersehen',
);
This can be integrated into an application with reasonable granularity (there can be many such files, e.g. one for each component) and control (you can easily fall back to any other language if you don't find a string) and it is also very convenient to modify without need for special tools.
My favorite PHP framework (Yii) and a giant open source project I have worked on (Moodle) also use this approach.
Noone of the two solutions seems great to me. You should think in the long run when you think a solution.
What if you choose to translate your website in other languages different from those you thought as russian or chinese? In the first case you have to add more and more columns, in the second you've to create more and more file. Another cons is what if you translate a page in italian and spanish but not yet in french?
I think that a good thing is to have a database based solution and a main language. Now you can do something like this:
Create a table 'page' (id, title, ...) where you'll store the page in the main language and where you'll have the info of the translated page too
Create a table 'translation' (idsource, idtranslation, language)
Everytime check the available translations and give those to the users
In database localization you have four main strategies. Each has particular advantages and disadvantages. For the long term I would definitely recommend cloning. You can see the four methods at the link below:
http://www.sisulizer.com/localization/software/server-desktop-database.shtml
There are two main ideas you want to be sure to be implementing. The first, be sure you are integrating some form of translation memory. Your language vendor should be instructing you on how to do this and probably doing it for you.
The second, for each additional language you target, your data will get at least 2x more complex. Keep this in mind as you move forward. Not only your data, but your file sets, management, etc.
Hope that helps. Let me know if you have further questions.
Russell
My current approach has been to use to _remap function provided by codeigniter to get the URI segment in order to check if the language is "en" or "np"
Here is a sample:
function _remap($url_title){
$this->_identify_language($this->uri->segment(1));
$data ['sub_categories'] = $this->category_model->get_category_list_by_url($url_title)->result_array();
$data ['news'] = $this->news_model->get_news_list_by_url($url_title)->result_array();
$data ['url_title'] = $url_title;
$this->_render_front_view('main',$data);
}
I am using this technique on every controller. Which is well not very efficient.
I wanted to ask if using sessions to store language codes would be better or is my current technique good enough?
Are there any other ways i can do this multi-lingual thing?
Of course my database is currently shaped for 2 lanaguages and i have seperated the fields. e.g:- title_en, title_np. these are echoed according to the language field used.
Lots of parts to this.
Your URL's do not really need to be /en/ and /fr/ unless you want it to be used for Google Analytics. Spidering doesn't make a lot of difference. Accept-Language headers can be just as reliable.
Globally parse this URL segment. You can use this method or the Accept-Language, but either way you need a hook, a MY_Controller or extend the Lang class.
Think about if you want the different languages to be totally seperate. For example, if I have an English page not translated to French, and the French page does not exist, should it show the English page or 404? You can either store the lang = fr in the database and take the value from a constant set in the hook/MY_Controller/etc.
WHERE lang = CURRENT_LANGUAGE
Structure your DB. title_en title_fr is one method, but it soon because unmanagable with lots of languages. Have a "pages" and "page_content" table, so that all generic information is in one table then all language specific (title, content, meta, etc) is in the page_conten table, which has a lang field.
There are a million ways to do all of this, but there is lots more to think about than just the URL. My favourite
I have been using this internationalization library for codeigniter and I find it suits my needs pretty well.
It extends the Lang class, and then in the constructor it parses the URI to figure out which language to use. So it is just loaded before you use any language files. You don't need to add any code to your controllers. It simply changes the setting in the language object. So you can retrieve the current language the same as you normally would:
$this->lang->lang();
If you have 500 news and 2 languages, changing url prefix in root will give you 1000 links, lets say "/en/hello-world" and "/np/hello-world" will have identical content and possibly the same title, which can be bad from SEO aspect. I would use session or cookies to store preferences, to preserve link juice.