How to translate a website into PHP?

Asked

Viewed 7,112 times

15

I’m making a simple website with just 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 saw that in PHP the syntax is very similar.

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

Expected exit:

english: TEXT

portuguese: TEXT

To extract the file .po I used the command xgettext and 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 the case of PHP file translation after this?

  • 2

    Take a look at this site, it might help: http://www.devin.com.br/php-gettext/

  • If you are in the habit of reading Ocs in English, here is another tutorial as well. http://www.onlamp.com/pub/a/php/2002/06/13/php.html

  • Thank you, @abfurlan, that’s what I needed!

  • It might be interesting to think of an alternative way. Translating the site, I imagine, is to have a site in more than one language, right? So I strongly recommend using a CMS, which already brings this ready for you. I know your site is small, but even so, a good CMS can greatly reduce your work. The best candidates are Wordpress and Joomla. Note: I have a site in Joomla, with parts made in PHP code.

  • @digofreitas wonder if you could give me some lights/tutos for beginners to create . po files and how to use gettext? Or some tool? I’m completely in the dark.

  • @Jorge-b just go on the link that romulos recommended, which explains very well

  • Thanks @digofreitas but I already got there alone ;)

Show 2 more comments

2 answers

19

The Gettext extension may not be available on the hosting service. It won’t help you much with translating Urls or BD records. Therefore, 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

It involves translating the fixed texts of your website, which are encoded directly in HTML (i.e., those texts that are not retrieved from a database). For this text create translation files and a function that maps it to you. Record the user’s language somewhere (session or cookie) so that you can know the user’s 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)

Create 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;

Translation of Urls

It involves the translation of the Urls of the site. For this to work it is necessary to use a single entry script for your site. Through a file . htaccess you can do this by redirecting any access to an index.php file. After redirecting, you can use a mapping of Urls, as well as done to 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).

  • 1

    You have covered a lot of ground with your response, including one that few sites take the trouble to do which is the translation of the Uris. But just missed the part that the author cited that is the use of Gettext. Could you complete? If not I assemble a nice text here.

  • The working principle of gettext is the same as that quoted in "Translation of static texts". However, if you want to use gettext you have a good tutorial on http://www.devin.com.br/php-gettext/. I particularly suggest using a framework that already incorporates translation classes/methods, such as Yii Framework (http://www.yiiframework.com/).

  • I don’t, thank you. : ) I also suggest a framework, at least one specific domain, only for translation at least, mainly because the Getteext is not a very consonant extension by hosting companies.

  • Exactly. That’s the problem with Gettext! :)

  • Thanks for the whim in the reply, @Arivan-Astos but really this approach was not what I wanted. I was able to accomplish everything I needed with this tutorial: http://www.devin.com.br/php-gettext/

  • 2

    Good answer. + 1. But the hint: "news" is countless in English. :)

Show 1 more comment

5


What I would do is:

1) created a folder named "lang"

2) placed 2 file Eng.php and (en.php or Eng.php) for 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 entire 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 for each word.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.