一、采用gettext,由于Smarty有相应得gettext的插件,所以就直接用这个插件了

注意:smarty-gettext-0.9.1.zip的README有错误,应为:

 

 

$smarty = new Smarty [...];
require('smarty-gettext.php'); 
$smarty->register_block('t', 'smarty_translate'); // 注意是下划线不是中划线(就因为这点把我害苦啦,老提示找不到相关函数,切记!!!)

 

 

步骤如下:

1.1  在公共的包含文件中加入如下的代码:

 

//$domain_info['lang']为cookie传进来的语言设定值
$language_code = $domain_info['lang'];
//界面语言设置成中文
if($language_code == 'zh_CN')
{
    
//设置目标语言
    putenv("LANG=$language_code");
    
setlocale(LC_ALL, $language_code);
    
//$package为mo文件的名字
    $package = 'i18n_zh';
    
//绑定mo文件的路径
    bindtextdomain($package, '/var/locale');
    
//设置搜索的mo文件的文件名
    textdomain($package);
    
//指定mo文件的返回到gettext的编码
    bind_textdomain_codeset($package, 'UTF-8');
}
elseif($language_code == 'BIG5')
{
    
//界面语言设置成繁体
    $language_code = 'zh_TW';
    
putenv("LANG=$language_code");
    
setlocale(LC_ALL, $language_code);
    
$package = 'i18n_tw';
    bindtextdomain(
$package, '/var/locale');
    textdomain(
$package);
    bind_textdomain_codeset(
$package, 'UTF-8');
}
else
{
    
//界面语言是英文
    //设置目标语言

    putenv("LANG=$language_code");
    
setlocale(LC_ALL, $language_code);
    
//$package为mo文件的名字
    $package = 'i18n_en';
    
//绑定mo文件的路径
    bindtextdomain($package, '/var/locale');
    
//设置搜索的mo文件的文件名
    textdomain($package);
    
//指定mo文件的返回到gettext的编码
    bind_textdomain_codeset($package, 'UTF-8');
}
//*********添加国际化语言的处理结束***************/

 

注意:以上代码中标红处的$language_code必须是系统中存在的语言代码,不能自定义,大小写也要一致

1.2 相应的模版中加入smarty插件要求的t标签

1.3 用smarty插件提供的工具 生成c文件

这个c文件是把所有的模版中加了标签的串提取出来了

 

 

php -./tsmarty2c.php  *.html > $package.c

 

 

注意:默认的c文件的名和1.1中定义的最好一样

需要注意的是tsmarty2c.php中定义的 smarty的open tag 和close  tag 必须与smarty配置文件设置的一致

1.4 调用linux系统得xgettext把1.3中的c文件生成后缀为po的文件

 

 

xgettext -$package    $package.c  --from-code=utf-8

 

 

注意:如果文件不是Asc编码的 还得在上面地命令中指明

--from-code=文件编码

1.5 编辑1.4中生成的$package.po ,加入相应的翻译对应串

有几种语言,就的分别编辑生成几个po文件

1.6 调用linux系统得msgfmt把1.3中的1.5中的po文件生成后缀为mo的 二进制文件

 

 

msgfmt -$package.mo $package.po

 

 

1.7 建立locale目录,要与1.1 中的bindtextdomain($package, '/var/locale');设置一样

以1.1中的为例,首先在/var/( 已有的)目录下建立locale目录,locale的结构为

 

 

|-- en_US
|   `-- LC_MESSAGES
|
|        -- $package.mo

|
|-- zh_CN
|   `-- LC_MESSAGES
|
|        -- $package.mo

|

`
-- zh_TW
`    
-- LC_MESSAGES
|          -- $package.mo

 

 

其中的第一层目录是按1.1 中的$language_code的定义设的,必须这样,否则找不到,第二层目录LC_MESSAGES是固定的,里面存放1.6 中生成的mo文件

说明:有时候可能修改了po重新生成了mo文件后,语言包不起作用,这时候重启一下apache就可以了

二、由于是网站用的是Smaty,我们可以把模板中的文字都提取出来,集中放到语言文件中
通过smarty的config_load来加载,前提把语言文件放到$smarty->config_dir所设定的目录中
只要在php中包含 ,如下的代码,

 

 

$smarty->config_load( 'chs.lang' );

//$lang为通过cookie或session获得的页面语言值

switch ($lang) { 

    
case 'zh-cn' :   

        
$smarty->config_load( 'chs.lang' );
        
break;     

    
case 'zh-tw' :   

        
header'cht.lang' ); 
        
break;   

    
default: 

        
header'cht.lang' ); 
        
break;   

}

 

 

 

 

 

php gettext 实现多语言

 

 

1.安装gettext

windows用户直接修改php.ini,开启php_gettext.dll扩展

ubuntu用户使用命令:sudo apt-get install php-gettext

centos用户如果编译安装php的时候没有使用–with-gettext参数,则有需要使用phpize编译安装gettext
进入php源码包,如 cd /usr/local/src/php/ext/gettext
执行phpize //运行后此目录下多出了一此configure文件
执行make && make install
按提示将生成的getext.so文件写入到php.ini中。如 extension=gettext.so;
重启apache,/etc/init.d/apache restart

2.配置语言环境

如果是debian系列的linux用户,注意查看本地语言支持,具体查看 /usr/share/i18n/SUPPORTED
例如:中文zh_CN.UTF-8
中文繁体zh_TW.UTF-8
英文en_US.UTF-8
如果没有相应语言,则安装它:suso apt-get locale-gen zh_CN.UTF-8

3.在php项目中使用gettext

在项目中创建语言包目录,例如:
简体中文:Locale/zh_CN/LC_MESSAGES
英文:Locale/en_US/LC_MESSAGES

语言包类:Locale.php

 

  1. <?php  
  2. /** 
  3.  * Locale 语言包类 
  4.  * 系统语言包采用的是php-getext模块 
  5.  * # 如果模板使用的是smarty.使用了smarty-gettext插件.插件地址http://sourceforge.net/projects/smarty-gettext/ 
  6.  *  php-gettext的安装和使用(ubuntu平台下) 
  7.  *  1 Installation of gettext package: sudo apt-get install php-gettext 
  8.  *  2 Install locales: see all locales in the file vim /usr/share/i18n/SUPPORTED 
  9.  *  2.1 如果没有相应语言则相应安装之。方法:sudo apt-get locale-gen zh_CN.UTF-8 
  10.  *  3 设置文件目录结构;如: Locale/zh_CN/LC_MESSAGES 或者 Locale/en_US/LC_MESSAGES 
  11.  *  4 如果是smarty模板(使用{t}你好{/t}标记)。生成.c格式的文件;如:php -q tsmarty2c.php  $file > text.c 
  12.  *  5 生成.po格式的文件;xgettext -o Dh.po --join-existing --omit-header --no-location text.c 
  13.  *  6 生成.mo格式的文件;msgfmt Dh.po -o Dh.mo 
  14.  *  7 移动mo文件到相应的Locale/en_US/LC_MESSAGES文件夹下面 
  15.  * @author administrator 
  16.  * 
  17.  */  
  18. class Locale  
  19. {  
  20.     /** 
  21.      * _options 设置语言包的选项 
  22.      * $this->_options['lang'] 应用程序使用什么语言包.php-gettext支持的所有语言都可以. 
  23.      * 在ubuntu下使用sudo vim /usr/share/il8n/SUPPORTED 主要是utf8编码 
  24.      * $this->_options['domain'] 生成的.mo文件的名字.一般是应用程序名 
  25.      * @var array 
  26.      * @access protected 
  27.      */  
  28.     protected $_options;  
  29.   
  30.     /** 
  31.      * 构造函数 
  32.      * 对象初始化是设置语言包的参数 
  33.      * @param string $lang 
  34.      * @access public 
  35.      * @return void 
  36.      */  
  37.     public function __construct($lang=null) {  
  38.         switch ( strtolower($lang) ) {  
  39.             case 'zh_tw':  
  40.                 $this->_options = array('lang' => 'zh_TW.UTF8''domain' => 'test');  
  41.                 break;  
  42.             case 'zh_cn':  
  43.                 $this->_options = array('lang' => 'zh_TW.UTF8''domain' => 'test');  
  44.                 break;  
  45.             case 'en':  
  46.                 $this->_options = array('lang' => 'en_US.UTF8''domain' => 'test');  
  47.                 break;  
  48.             case 'en_us':  
  49.                 $this->_options = array('lang' => 'en_US.UTF8''domain' => 'test');  
  50.                 break;  
  51.             case 'en_gb':  
  52.                 $this->_options = array('lang' => 'en_US.UTF8''domain' => 'test');  
  53.                 break;  
  54.             default:  
  55.                 $this->_options = array('lang' => 'zh_TW.UTF8''domain' => 'test');  
  56.             break;  
  57.         }  
  58.   
  59.         $this->setApplicationLocale();  
  60.     }  
  61.   
  62.     /** 
  63.      * 设置应用程序语言包的参数,放在$this->_options中 
  64.      * @param mixed $options 
  65.      * @return void 
  66.      */  
  67.     public function setOptions($options) {  
  68.         if (!emptyempty($options)) {  
  69.             foreach ($options as $key => $option) {  
  70.                 $this->_options[$key] = $option;  
  71.             }  
  72.         }  
  73.     }  
  74.   
  75.     /** 
  76.      * 设置应用程序语言包 
  77.      * @access public 
  78.      * @return void 
  79.      */  
  80.     public function setApplicationLocale() {  
  81.         putenv('LANG='.$this->_options['lang']);  
  82.         putenv('LANGUAGE='.$this->_options['lang']);  
  83.         setlocale(LC_ALL, $this->_options['lang']);  
  84.         bindtextdomain($this->_options['domain'], PROJECTDIR.'/locale/');  
  85.         textdomain($this->_options['domain']);  
  86.         bind_textdomain_codeset($this->_options['domain'], 'UTF-8');  
  87.     }  
  88.   
  89. }  
  90.   
  91. ?>  

 

使用方法:

 

  1. $lang = 'zh_TW';  
  2. $locale = new Locale($lang);  

 

 

 

 

 

根据上述提供的例子,再加上自己动手制作的经历,有以下笔记:

 

1.我用的是Smarty-3.0.8 版本,上面这个“块函数” 

$smarty->register_block('t', 'smarty_translate');

 已过时,即不存在了,要改为

 

$smarty->registerPlugin("block",'t', 'smarty_translate');

 

它的作用是把smarty模板中的 <{t}>*** <{/t}> 当作块函数使。

 

2.把以命令行形式生成的*.c文件过程,改成了用http方法页面的形式生成,调整tsmarty2c.php 文件如下:

访问地址如下:http://localhost/wjy_ws_zoo/Server/tsmarty2c.php

 

<?php
#!/usr/local/bin/php -qn
/*
*
 * tsmarty2c.php - rips gettext strings from smarty template
 *
 * ------------------------------------------------------------------------- *
 * This library is free software; you can redistribute it and/or             *
 * modify it under the terms of the GNU Lesser General Public                *
 * License as published by the Free Software Foundation; either              *
 * version 2.1 of the License, or (at your option) any later version.        *
 *                                                                           *
 * This library is distributed in the hope that it will be useful,           *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of            *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU         *
 * Lesser General Public License for more details.                           *
 *                                                                           *
 * You should have received a copy of the GNU Lesser General Public          *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *
 * ------------------------------------------------------------------------- *
 *
 * This command line script rips gettext strings from smarty file, and prints them to stdout in C format, 
 * that can later be used with the standard gettext tools.
 *
 * Usage:
 * ./tsmarty2c.php <filename or directory> <file2> <..> > smarty.c
 *
 * If a parameter is a directory, the template files within will be parsed.
 *
 * @package    smarty-gettext
 * @version    $Id: tsmarty2c.php,v 1.2 2004/04/30 11:40:22 sagi Exp $
 * @link    http://smarty-gettext.sf.net/
 * @author    Sagi Bashari <sagi@boom.org.il>
 * @copyright 2004 Sagi Bashari
 
*/

 
header("Content-type:text/html;charset=utf-8"); 
 
 
// smarty open tag
$ldq = preg_quote('<{');

// smarty close tag
$rdq = preg_quote('}>');

// smarty command
$cmd = preg_quote('t');

// extensions of smarty files, used when going through a directory
//$extensions = array('tpl');


$extensions = array('html');

$echotext="";

// "fix" string - strip slashes, escape and convert new lines to \n
function fs($str)
{
    
$str = stripslashes($str);
    
$str = str_replace('"', '\"', $str);
    
$str = str_replace("\n", '\n', $str);
    
return $str;
}

// rips gettext strings from $file and prints them in C format
function do_file($file)
{
    
global $echotext;
    
    
$content = @file_get_contents($file);

    
if (empty($content)) {
        
return;
    }

    
global $ldq, $rdq, $cmd;

    
preg_match_all("/{$ldq}\s*({$cmd})\s*([^{$rdq}]*){$rdq}([^{$ldq}]*){$ldq}\/\\1{$rdq}/", $content, $matches);
    
    
for ($i=0$i < count($matches[0]); $i++) {
        
if (preg_match('/plural\s*=\s*["\']?\s*(.[^\"\']*)\s*["\']?/', $matches[2][$i], $match)) {
            
//print 'ngettext("'.fs($matches[3][$i]).'","'.fs($match[1]).'",x);'."\n";
            $echotext.='ngettext("'.fs($matches[3][$i]).'","'.fs($match[1]).'",x);'."\n";
        } 
else {
            
//print 'gettext("'.fs($matches[3][$i]).'");'."\n";
            $echotext.='gettext("'.fs($matches[3][$i]).'");'."\n";
        }
    }
}

// go through a directory
function do_dir($dir)
{
    
$d = dir($dir);

    
while (false !== ($entry = $d->read())) {
        
if ($entry == '.' || $entry == '..') {
            
continue;
        }

        
$entry = $dir.'/'.$entry;

        
if (is_dir($entry)) { // if a directory, go through it
            do_dir($entry);
        } 
else { // if file, parse only if extension is matched
            $pi = pathinfo($entry);
            
            
if (isset($pi['extension']) && in_array($pi['extension'], $GLOBALS['extensions'])) {
                do_file(
$entry);
            }
        }
    }

    
$d->close();
}

/*
for ($ac=1; $ac < $_SERVER['argc']; $ac++) {
    if (is_dir($_SERVER['argv'][$ac])) { // go through directory
        do_dir($_SERVER['argv'][$ac]);
    } else { // do file
        do_file($_SERVER['argv'][$ac]);
    }
}
*/


//do_file('d:/php/xampp/htdocs/wjy_ws_zoo/Server/module/test/views/index.html');
//do_dir('d:/php/xampp/htdocs/wjy_ws_zoo/Server/module/test/views');


do_dir(
'./module/test/views');
writefile(
$echotext);
echo $echotext;



function writefile($writetext,$filename='default.c', $openmod='w') {
    
if(@$fp = fopen($filename, $openmod)) {
        
flock($fp, 2);
        
fwrite($fp, $writetext);
        
fclose($fp);
        
return true;
    } 
else {
        
//log_runlog('error', "File: $filename write error.");
        print("write error");
        
return false;
    }
}

?>

 

 模板文件如下:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<href=”http://sourceforge.net/projects/smarty-gettext/”><{t}>点击下载插件<{/t}></a>
<href=”http://sourceforge.net/projects/smarty-gettext/”><{t}>哈哈<{/t}></a>
<href=”http://sourceforge.net/projects/smarty-gettext/”><{t}>哦哦<{/t}></a>
<href=”http://sourceforge.net/projects/smarty-gettext/”><{t}>嘻嘻<{/t}></a>
<href=”http://sourceforge.net/projects/smarty-gettext/”><{t}>拜拜罗<{/t}></a>
</body>
</html>

 

届时项目目录下即有个 default.c 文件 

 

 

 

其他笔记如下:

 

1.制作全局的多国语言配置信息(现在的情况是把 中文 翻译成 英文)

    
//多国语言配置 by wenjianbao
    putenv ('LANG=en_US' );
    
setlocale ( LC_ALL, 'en_US' );
    
$domain  =  'default' ; //定义要用的语言文件名称  
    bindtextdomain ( $domain ,  dirname(__FILE__).'/locale' );     //设置某个域的mo文件路径 // 设置mo文件的路径,这里的路径为 locale/en_US/LC_MESSAGES/default.mo   
    bind_textdomain_codeset($domain ,  'UTF-8' );  //设置mo文件的编码为UTF-8    
    textdomain($domain );//设置gettext()函数从哪个域去找mo文件   
    
2.通过php文件:http://localhost/wjy_ws_zoo/Server/tsmarty2c.php
  把模板文件夹“\module\test\views\”内的所有的*.html文件生成default.c文件

3.把default.c文件生成default.mo文件
  xgettext 
-default    default.c  --from-code=utf-8

4.编译default.mo文件
  msgfmt 
-default.mo default.po

5.把default.po文件拷贝到 “locale/en_US/LC_MESSAGES/” 文件夹下

 

 

 

 

 

 

 

 

 

posted on 2011-09-01 11:08  小炒花生米  阅读(3396)  评论(1编辑  收藏  举报