Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gettext() equivalent in Intl library?

Tags:

php

gettext

intl

I'm looking for a way to to do i18n and l10n.

I've used gettext before and it was good: I would simply create .mo files in different languages and everything that needed to be translated would be in this notation:

echo __('string to be translated');

I know that there is Intl library built into PHP now, and I've been told that I should use it instead of gettext().

After reading through everything there is about Intl on php.net, I see that it has some nice features like locale handling, string comparison, number formatting, etc.

What I can't figure out is how I would handle regular string to string translation using Intl library. Any ideas?

like image 870
Stann Avatar asked Apr 13 '11 04:04

Stann


2 Answers

That advise wasn't very truthful. The intl functions can be used in conjunction to gettext, not as replacement.

MessageFormatter is what people have in mind when they associate INTL with text translations. The examples suggest so. But in reality it's just a sprintf on steroids. It injects numbers into existing strings. (I'm not even sure how the locale support is of any use there, as it just serves as internal switch.)

like image 108
mario Avatar answered Sep 19 '22 18:09

mario


Here's how I used intl for translations (tested on php v. 5.3.10 and 5.4.7):

intl.php

namespace Example;
class Intl {

  private $resource;

  public function __construct() {
    $bundle_location = "./locales";
    $user_locale = \Locale::acceptFromHttp( $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
    $this->resource = new \ResourceBundle( $user_locale, $bundle_location );
  }

 ...

display.php

 use Example\Intl;

 $intl = new Intl();
 $r = $intl->resource;

 echo $r['string_to_be_translated'];

 ...

resource bundles

In the locales directory, I have my resource files:

root.res - root language (English)

root { 
  string_to_be_translated {String to be translated } 
}

ja.res - Japanese

ja { 
  string_to_be_translated {\u5909\u63DB\u3055\u308C\u308B\u6587\u5B57\u5217 }
}

sp.res - Spanish

sp { 
  string_to_be_translated {Cadena a ser traducido }
}

(etc)

like image 43
BryanH Avatar answered Sep 17 '22 18:09

BryanH