Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use po/pot files with php?

I have a .po and a .mo file in a folder whose address is /locale/nld_nld/LC_MESSAGES/. Both the files' names are messages. I've been trying to use the following code:

try.php:

<?php
require_once("Localization.php");
echo _("Hello World!");
?>

the Localization.php goes here:

<?php
$locale = "nld_nld";
if (isSet($_GET["locale"])) $locale = $_GET["locale"];
putenv("LC_ALL=$locale");
setlocale(LC_ALL, $locale);
bindtextdomain("messages", "./locale");
bind_textdomain_codeset("messages", 'UTF-8');
textdomain("messages");
?>

Both the try.php and the Localization files are in the same directory. Also, I use xampp. I also implemented the phpinfo();. In the table, in front of 'GetText Support', enabled was mentioned. The messages.po and the messages.mo files are valid files which I created using poEdit. I'm a windows user. However, when I opened try.php, it simply echoed Hello World! (not its translated string. Also, I've translated the .po file 100% (according to poEdit). Still, I'm not getting the results. A little help on this would be appreciated.

Thanks in advance!

like image 674
Rajat Sharma Avatar asked Nov 06 '22 04:11

Rajat Sharma


1 Answers

When looking back at code I have in place on a working site for spanish translation, I notice I also have the same lines in a different order, perhaps that makes a difference? For example:

<?php
putenv('LC_MESSAGES=es_ES');
setlocale(LC_MESSAGES, 'es_ES.utf8');
bindtextdomain('es','/full/path/here/application/locale');
textdomain('messages-es');
bind_textdomain_codeset('messages-es', 'UTF-8');
?>

For the above code to work, my .mo file is in the /full/path/here/application/locale/es_ES.utf8 folder.

Perhaps the following code I've used before might help you troubleshoot further:

<?php
function TestLang( $langCode ) {
  echo( '<b>TESTING LANG CODE: ' . strtolower( $langCode ) . '</b><br />' );
  putenv( 'LC_MESSAGES=' . strtolower( $langCode ) . '_' . strtoupper( $langCode ));
  echo( 'LC_MESSAGES: ' . getenv( 'LC_MESSAGES' ) . '<br />' );
  $localeResult = setlocale( LC_MESSAGES, strtolower( $langCode ) . '_' . strtoupper( $langCode ) . '.utf8' );
  echo( 'Locale: ' . $localeResult . '<br />' );
  $textDomain = bindtextdomain( strtolower( $langCode ), ROOT . '/' . APP_DIR . '/locale' );
  echo( 'Text Domain: ' . $textDomain . '<br />' );
  textdomain( strtolower( $langCode ));
  $codeSet = bind_textdomain_codeset( strtolower( $langCode ), 'UTF-8' );
  echo( 'Code Set: ' . $codeSet . '<br />' );
  echo( '.mo File: ' . $textDomain . '/' . $localeResult . '/LC_MESSAGES/' . $langCode . '.mo<br />' );
  echo( '<br />-- ' . _( 'Hello World!' ) . ' --<br />' );
}

TestLang( 'en' );
TestLang( 'de' );
TestLang( 'es' );
TestLang( 'fr' );
// etc..
?>
like image 130
richhallstoke Avatar answered Nov 14 '22 17:11

richhallstoke