How to translate a website in PHP?

I am making a simple website with only a few pages PHP . I would like this page to be translatable to Portuguese and English. I already use the function gettext in python and I saw that in PHP the syntax is very similar.

Code: gettext('TEXT') or _('TEXT')

Expected output:

English: TEXT

English: text

To extract the file .po I used the command xgettext and I managed to generate the translation file and convert to binary . mo quietly. But my biggest difficulty is to load the translation files in PHP and make it work properly.

How Should I proceed in case of PHP file translation after this?

 15
Author: rray, 2014-05-15

2 answers

What I would do was:

1) created a folder with the name "lang"

2) put 2 file eng.php e (pt.php or eng.php) example: eng.php

    <?php 
      $titulo = "My title";
    ?>

Pt.php

    <?php 
      $titulo = "O meu titulo";
    ?>

3) would make a button that added index.php?lang = en, for the case of English

4) throughout the site I assigned variables and in those files I used them to put the respective translation used.

    if($_GET['lang'] == "en"){
        include 'eng.php';
     }
<html>
    <head>
      <title> <?php echo $titulo; ?></title>
    </head>
    <body>

    </body>
</html>

This way would avoid using a database to every word.

I hope I helped.

 5
Author: Amadeu Antunes, 2019-07-14 02:28:37

The gettext extension may not be available on the hosting service. In addition, it will not help you much with translation of URLs or database records. So my suggestion is that you work with a more complete translation system, which can be deployed on any PHP site without dependency on the gettext extension. This solution involves 3 parts:

Translation of static texts

Involves translating the fixed texts of your site, which are encoded directly in HTML (that is, those texts that are not retrieved from a database). For this text create translation files and a function that maps it for you. Record the user's language somewhere (session or cookie) so that you can know their preference and which mapping to use:

En_us.php

<?php
return array(
    'A Empresa'=>'The Company',
    'Contato'=> 'Contact',
    ...
);

Translator.php

<?php
function _($text)
{
     session_start();         

     // Exemplo recuperando o idioma da sessao.
     $lang = isset($_SESSION['lang'])?$_SESSION['lang']:'';

     if (!empty($lang))
     {
          // Carrega o array de mapeamento de textos.
          $mapping = require_once $lang.'.php';
          return isset($mapping[$text])?$mapping[$text]:$text;
     }

     return $text;
}

Example-of-use.php

<?php
require_once 'translator.php';
session_start();

// Apenas para teste. O idioma deve ser
// escolhido pelo usuário.
$_SESSION['lang'] = 'en_us';

echo _('Contato');

Translation of dynamic texts (from the database)

Shout an additional column in each table, which specifies the language of the record. For example, a news table could be:

id    titulo              texto                    data          **idioma_id**
----------------------------------------------------------------------------
1     Noticia de teste    Apenas uma noticia      2014-05-16     1
2     Test new            Just a new              2014-05-16     2

When consulting the records, bring only those of the desired language:

SELECT * FROM noticia WHERE idioma_id = 2;

URL translation

Involves translating site URLs. For this to work it is necessary to use a single input script for your website. Through a file .htaccess you can do this by redirecting any access to an index file.php. After redirecting, you can use a mapping of the URLs, as well as done for the static texts:

.htaccess

RewriteEngine on

# Nao aplica o redirecionamento caso 
# o que esteja sendo acessado seja um arquivo ou pasta.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Redireciona para o arquivo index.php
RewriteRule . index.php

En_us_routes.php

<?php
    return array(
        'the-company'=>'a_empresa.php',
        'contact'=> 'contato.php',
        ...
    );

Index.php

// Remove da URL a pasta da aplicacao,
// deixando apenas os parametros.
$aux = str_replace('index.php', '', $_SERVER['SCRIPT_NAME']);
$parameters = str_replace($aux, '', $_SERVER['REQUEST_URI']);

// Recupera as partes da URL.
// Se você acessar http://meusite.com.br/empresa
// $urlParts será:
//      array('empresa')
//
// Se você acessar http://meusite.com.br/contato
// $urlParts será:
//      array('contato')
$urlParts = explode('/', $parameters);

// Para simplificar, aqui trata uma URL com
// apenas uma parte. Mas você pode generalizar para urls
// com suburls também (Ex: "empresa/onde-estamos").
$url = $urlParts[0];

// Apenas para teste. O idioma pode estar
// associado ao perfil do usuário e ser setado
// na sessão no login.
$_SESSION['lang'] = 'en_us';

// Carrega o array de mapeamento de URLs.
$mappingFileName = $_SESSION['lang'].'_routes.php';
$mapping = require_once $mappingFileName ;

if (isset($mapping[$url]))
{
    require_once $mapping[$url];
}
else
{
    require_once 'erro_404.php';
}

The codes cited are just examples to pass the idea (have not been tested).

 19
Author: Arivan Bastos, 2018-03-02 01:06:08