There are several ways to define different languages for your site. Perhaps the most recommended is to use Gettext a GNU
library.
An alternative way (and use) is to use javascript
objects and link them to your page and use a function in javascript
to "translate" the source.
A simple example would be to define a file (object) by default and load others by iterating the user with $_POST
for example.
However note that this "translation" would only occur after the load
of the page other than gettext
which already translates to the PHP
output.
This option also delegates to the user the cost of this processing so there is an observation that may not be recommended for use with a large volume source.
It would also be possible to create a cookie
to remember the language option of the user plus this issue will not be addressed 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 plus you can use | adapt via jQuery
to facilitate for example: "preppends" or "appends" can be used to define placeholders, titles, alt, etc ...
To insert values coming from reference by PHP
as from the database simply put the values following this logic within the 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 index and sub-indices within 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 (finalized) source code that is not extensive I believe it is a good alternative because caching javascript
files will not impact the user experience for the site.
Now for constant maintenance projects every time there are changes in the language files the user will have to download again to cache.
Note: Functional example.