How to translate a website in PHP?


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

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

Expected output:

English: TEXT

Portuguese: TEXT

To extract the .po file I used the command xgettext and managed to generate the translation file and convert to binary .mo quietly. But my biggest problem is loading the translation files into PHP and getting them to work correctly.

How do I proceed in case of translation of PHP files after this?

asked by anonymous 15.05.2014 / 17:41

2 answers


What I would do was:

1) created a folder named "lang"

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

      $titulo = "My title";


      $titulo = "O meu titulo";

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

4) At the logo of the whole site I assigned variables and in that files I used them to put the respective translation used.

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


In this way you would avoid using a database for each word.

I hope I have helped.

07.02.2017 / 23:06

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

Static text translation

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


return array(
    'A Empresa'=>'The Company',
    'Contato'=> 'Contact',


function _($text)

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


require_once 'translator.php';

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

echo _('Contato');

Translation of dynamic (database) texts

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 looking at the records, bring only those of the desired language:

SELECT * FROM noticia WHERE idioma_id = 2;

URL Translation

Involves translation of site URLs. For this to work you need to use a single login script for your site. Through an .htaccess file you can do this by redirecting any access to an index.php file. After redirecting, you can use a URL mapping, just like for static text:


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


    return array(
        'contact'=> 'contato.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
// $urlParts será:
//      array('empresa')
// Se você acessar
// $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];
    require_once 'erro_404.php';

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

17.05.2014 / 03:37