Web translating - single or separate files for different languages? - php

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.

Related

Add URI Segment for Language in Codeigniter

I have a site; I need to develop to support multiple languages, for example en, tr, ar, sp, etc.
But the problem is , what is the best way to do it with Codeigniter?
I have a controller ( SITE ). I have a lot of functions LIKE ( hotel , city , page , blog )
I want to before this method add a segment ( language ). This is old links
http://example.com/hotel/mariot
http://example.com/hotel/hilton
http://example.com/city/london
http://example.com/city/paris
...
..
and I want the links to be like this
http://example.com/en/hotel/mariot
http://example.com/ar/hotel/mariot
http://example.com/sp/hotel/mariot
http://example.com/tr/hotel/mariot
http://example.com/en/city/london
http://example.com/ar/city/paris
....
..
sometimes thinking every language have a controller but it is possible...
What is the best way to change all links to support the languages?
I'm sorry If my question is not clear, this is my English.
The right way, is using routes.php look for it inside (application/config/routes.php)
You can use regex expressions for your specific problem.
here is the manual: http://ellislab.com/codeigniter/user-guide/general/routing.html
if you want your links to be like this
http://example.com/en/something
then you might need to have subdomain or folder in your project called en. but yet this is not the perfect solution.
what you have to do is to make your text output assigned into variables which takes their values from an xml file. like if you have some text called "your room number is: 0" and this value is hard coded HTML then you should put it in en.xml file under some tag and get it from the xml file which is requested by the user according to the required lang.
you might can do the previous solution in all languages but you have to consider that Arabic language is RTL language so just consider that in your css. But generally you can use xml files to control the languages.
hope that is what you needed.

How to dynamically change website's language using PHP-MySQL?

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

Php multilingual website

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.

Best way to build a multilingual site with codeigniter?

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.

Create redirect URL

Here is the real case, in the NewsNow.co.uk, there are many link of uptodate news from thousands of website. And the example for one of the news url:
http://newsnow.co.uk/A/471722742?-19721
all the news url are formated like that, but when we click it, we will be brought to the real url, for ex:
http://www.abcactionnewsx.com/dpp/news/state/bla-bla
anyone know how to achieve this efficiently ?
Store a table of 'internal' paths (the 'newsnow' urls) and the 'destination' urls in a database of some sort; sqlite3 would be a fine choice for smaller applcations.
You could hash the 'internal' paths if lookup time for specific strings was too slow in the database you chose.
When a request comes in, look it up in the database and send back a 302 response with the 'target' URL as the new location for the resource.
This is done using a rewrite engine that is built into common webservers like Apache or Nginx. These engines allow you to write rules that transform a url like the first one into something that would be better understood by your php pages. For example, you could create rules that would turn your first link above into:
http://newsnow.co.uk/index.php?catagory=A&id=471722742&referrer=-19721
This is transparent to the user and they will only ever see the link they first typed in. You can then use the variables being passed in to perform whatever actions you desire. In this case you might want to use the variables to perform some kind of database lookup to retrieve the actual destination that you are interested in. Then it's just a question of performing a php redirect to the link in question.
Check out the following link for a very quick intro to Apache's rewriting capabilities (called mod_rewrite): http://www.besthostratings.com/articles/mod-rewrite-intro.html

Categories