There are several ways to define different languages to the site. Perhaps the most recommended is to use Gettext a library GNU
.
An alternative way (and what use) is to use objects javascript
and links to your page and use a function in javascript
to "translate" the source.
A simple example would be to set a file (object) as default and load others by user iteration with $_POST
for example.
However note that this "translation" would only occur after the load
of the page other than gettext
which already translates in the output of PHP
.
This option also delegates to the user the cost of this processing so there is the observation that may not be recommended to be used with a large volume source.
It would also be possible to create a cookie
to remember the language option of the bad user this issue will not address in the example.
index php.
<?php
// array de idiomas permitidos
$allowed_languages = ['en-US','pt-BR'];
// verificar se houve um post e se é um valor permitido
if( isset($_POST['lang']) AND in_array($_POST['lang'], $allowed_languages) ){
// definir o novo caminho
$lang_path = 'path/tojslanguage/i18n_'.$_POST['lang'].'.js';
// salvar em sessão (para recuperar e outros pontos ou no reload)
$_SESSION['lang'] = $_POST['lang'];
}else{
// verificar se ha sessão
if( isset($_SESSION['lang']) ){
// recuperar
$lang_path = 'path/tojslanguage/i18n_'.$_SESSION['lang'].'.js';
}else{
// definir um valor padrão
$lang_path = 'path/tojslanguage/i18n_en-US.js';
// salvar sessão (valor default)
$_SESSION['lang'] = 'en-US';
}
}
// Neste ponto seria interessante utilizar a sessão na tag `<html lang="">`
?>
<!DOCTYPE html>
<html lang="">
<head>
<title></title>
</head>
<body>
<!--
os atributos recomendados para servirem de referencia ao javascript
seriam: "class" e "data-".
como exemplo deixo uma h1 a ser traduzida e botões para disparar a ação
-->
<h1 data-html="words.title" class="i18n"></h1>
<button id="en-US" data-html="words.USlang" class="i18n choose-lang"></button><br>
<button id="pt-BR" data-html="words.BRlang" class="i18n choose-lang"></button>
<script type="text/javascript" src="<?php echo $lang_path; ?>"></script>
<script type="text/javascript">
//
var wd = window,
dc = document,
XHR = (new XMLHttpRequest()),
FD = (new FormData());
// função para disparar um post
var requestPost = function(url, params, callback){
// catch response
XHR.onreadystatechange = function(){
if(XHR.readyState == 4 && XHR.status == 200){
if(callback){
callback(XHR.responseText);
}
}
}
// open
XHR.open('POST', url, true);
/**
* set header [obsolete in use FormData API]
* XHR.setRequestHeader('Content-type','application/x-www-form-urlencoded; charset=UTF-8');
*/
// check
if(!params || typeof params !== 'object' || Object.keys(params).length < 1){
return false;
}else{
var keys = Object.keys(params),
i = keys.length;
// loop (inverse)
while(i--){
FD.append(keys[i], params[keys[i]]);
}
// send
XHR.send(FD);
}
};
var choose_lang = dc.getElementsByClassName('choose-lang');
//loop
for(var i = 0; i < choose_lang.length; i++){
//
choose_lang[i].addEventListener('click', function(){
// recupar o id (idioma)
var language = this.getAttribute('id');
requestPost('./', {lang: language});
location.reload(true);
});
}
var ilib = function(){
// buscar referencia
var set = dc.getElementsByClassName('i18n');
// fazer o loop para buscar todas as referencias
for(var i = 0; i < set.length; i++){
// capturar a referencia do objecto
var html = set[i].getAttribute('data-html');
// checar se há (existe) valor definido
if(!!html && typeof html !== undefined){
// separar referencias
var transc = set[i].getAttribute('data-html').split('.');
/**
checar o número de palavras...
note neste exemplo apenas duas más é possíveis definir varias
*/
if(transc[2]){
var word = i18n[transc[0]][transc[1]][transc[2]];
}else{
var word = i18n[transc[0]][transc[1]];
}
// aplicar tradução
set[i].innerHTML = word;
}
}
};
// dispara tradução após carregar a página
wd.onload = ilib();
</script>
</body>
</html>
i18n_en-US.js
var i18n = {
words: {
title: 'Welcome to site.com',
USlang: 'Englis (USA)',
BRlang: 'Portuguese (Brazil)'
}
};
i18n_en-BR.js
var i18n = {
words: {
title: 'Bem vindo ao site.com',
USlang: 'Ingles (USA)',
BRlang: 'Portugues (Brasil)'
}
};
This example is in javascript
pure but it is possible to use|adapt route jQuery
to facilitate for example: "preppends" or "appends" is possible to use to define placeholders, Titles, alt, etc...
To insert values from reference by PHP
as the database just put the values following this logic inside the atibuto data-html=""
.
example:
<?php
// exemplo ficticio de um valor salvo no banco de dados
$value = 'words.palavara_qualquer';
?>
<a data-html="<?php echo $value; ?>" class="i18n" href="#"></a>
In these examples it is possible to create an Indice and sub-indices inside the object:
// o objeto em si (i18n)
var i18n = {
// um indice (words)
words: {
// um sub-indice (ou item)
title: 'Uma palavra qualquer um uma frase'
},
// outro indice
teplates: {
// um sub-item de templates
dark: 'Escuro'
}
};
For a stable source code (finished) and that is not extensive I believe it is a good alternative because caching the files javascript
will not impact the user’s experience with the website.
Now for maintenance projects every time there are changes in language files the user will have to download again for caching.
Note: functional example.
You can take a look at: How to translate a website into PHP?, How to make a multilingual site? and Website in two languages
– rray