Federico Schiocchet
Federico Schiocchet

Reputation: 177

PHP - Function gettext() not work

I have setted everything correctly and with all the possible variants but gettext never work, below my settings, and here the details:

  1. Tested on both Windows with XAMPP and Linux.
  2. Gettext is active on php.ini and with WordPress work good always.
  3. I confirm that the .mo and .po files are correct due work good with WordPress, created with Poedit.
  4. I inserted the files it_IT.mo, it_IT.po, it.mo, it.po, domain.mo, domain.po (where domain is my domain) into the following folders:

    • C:\xampp\htdocs\sbphp\sb\lang
    • C:\xampp\htdocs\sbphp\sb\lang\it
    • C:\xampp\htdocs\sbphp\sb\lang\it_IT
    • C:\xampp\htdocs\sbphp\sb\lang\locale\LC_MESSAGES\it
    • C:\xampp\htdocs\sbphp\sb\lang\locale\LC_MESSAGES\it_IT
    • C:\xampp\htdocs\sbphp\sb\lang\locale\it
    • C:\xampp\htdocs\sbphp\sb\lang\locale\it_IT
    • C:\xampp\htdocs\sbphp\sb\lang\LC_MESSAGES\it
    • C:\xampp\htdocs\sbphp\sb\lang\LC_MESSAGES\it_IT

My code is this:

putenv('LANGUAGE=it'); //Variants: it_IT - it_IT.UTF-8- it.UTF-8
putenv('LC_ALL=it'); //Variants: it_IT - it_IT.UTF-8- it.UTF-8
putenv('LANG=it'); //Variants: it_IT - it_IT.UTF-8- it.UTF-8
define('PROJECT_DIR', realpath('./')); //Variants: without this constant
define('LOCALE_DIR', "../lang"); //Variants: without this constant
define('DEFAULT_LOCALE', 'it_IT'); //Variants: without this constant
$results =  setlocale(LC_ALL, array('it_IT.UTF-8', 'it.UTF-8', 'it')); //Return 'it'
$results =  bindtextdomain($domain, "../lang"); //It return the correct path C:\xampp\htdocs\sbphp\sb\lang - Variants: Locale - locale
$results =  bind_textdomain_codeset($domain, 'UTF-8');
$results =  textdomain($domain);
return gettext($string);

And never work.

My Problem:

setlocale(); returns "it", If I set wrong values returns false.

bindtextdomain(); Returns the correct path C:\xampp\htdocs\sbphp\sb\lang, If I set wrong values it returns nothing.

bind_textdomain_codeset Returns UTF-8.

bind_textdomain_codeset() returns my correct domain. So I think there is not any error here. The output is the original (not translated) text.

Upvotes: 0

Views: 587

Answers (1)

Federico Schiocchet
Federico Schiocchet

Reputation: 177

I found the solution, use this library https://github.com/oscarotero/Gettext solved the problem immediately.

Installation

require("gettext/autoloader.php");
use Gettext\Translations;
$translations_file;

Usage

function translate($string,$lang = "en_EN") {
    global $translations_file;
    if (!isset($translations_file)) {
        $translations_file = Translations::fromPoFile('../your-path/' . $lang . ".po");
    }
    $translation = $translations_file->find(null, $string);
    $result = $translation->getTranslation();
    if ($result != "") {
        return $result;
    } else {
        return $string;
    }
}

Upvotes: 1

Related Questions