gettext() equivalent in Intl library?

只愿长相守 提交于 2020-01-10 14:10:36

问题


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?


回答1:


You'd use gettext. Intl (like ICU underneath it) is for l10n, not loading translations.




回答2:


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.)




回答3:


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)



来源:https://stackoverflow.com/questions/5644412/gettext-equivalent-in-intl-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!