设为首页 收藏本站
查看: 1688|回复: 0

[经验分享] PHP Smarty通过gettext制作多语言版本

[复制链接]

尚未签到

发表于 2015-8-25 06:56:06 | 显示全部楼层 |阅读模式
  一、采用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 -q ./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 -d $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 -o $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;   
}  
  
  
DSC0000.gif
  
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
  

  • <?php  
  • /**
  • * Locale 语言包类
  • * 系统语言包采用的是php-getext模块
  • * # 如果模板使用的是smarty.使用了smarty-gettext插件.插件地址http://sourceforge.net/projects/smarty-gettext/
  • *  php-gettext的安装和使用(ubuntu平台下)
  • *  1 Installation of gettext package: sudo apt-get install php-gettext
  • *  2 Install locales: see all locales in the file vim /usr/share/i18n/SUPPORTED
  • *  2.1 如果没有相应语言则相应安装之。方法:sudo apt-get locale-gen zh_CN.UTF-8
  • *  3 设置文件目录结构;如: Locale/zh_CN/LC_MESSAGES 或者 Locale/en_US/LC_MESSAGES
  • *  4 如果是smarty模板(使用{t}你好{/t}标记)。生成.c格式的文件;如:php -q tsmarty2c.php  $file > text.c
  • *  5 生成.po格式的文件;xgettext -o Dh.po --join-existing --omit-header --no-location text.c
  • *  6 生成.mo格式的文件;msgfmt Dh.po -o Dh.mo
  • *  7 移动mo文件到相应的Locale/en_US/LC_MESSAGES文件夹下面
  • * @author administrator
  • *
  • */  
  • class Locale  
  • {  
  •     /**
  •      * _options 设置语言包的选项
  •      * $this->_options['lang'] 应用程序使用什么语言包.php-gettext支持的所有语言都可以.
  •      * 在ubuntu下使用sudo vim /usr/share/il8n/SUPPORTED 主要是utf8编码
  •      * $this->_options['domain'] 生成的.mo文件的名字.一般是应用程序名
  •      * @var array
  •      * @access protected
  •      */  
  •     protected $_options;  
  •   
  •     /**
  •      * 构造函数
  •      * 对象初始化是设置语言包的参数
  •      * @param string $lang
  •      * @access public
  •      * @return void
  •      */  
  •     public function __construct($lang=null) {  
  •         switch ( strtolower($lang) ) {  
  •             case 'zh_tw':  
  •                 $this->_options = array('lang' => 'zh_TW.UTF8', 'domain' => 'test');  
  •                 break;  
  •             case 'zh_cn':  
  •                 $this->_options = array('lang' => 'zh_TW.UTF8', 'domain' => 'test');  
  •                 break;  
  •             case 'en':  
  •                 $this->_options = array('lang' => 'en_US.UTF8', 'domain' => 'test');  
  •                 break;  
  •             case 'en_us':  
  •                 $this->_options = array('lang' => 'en_US.UTF8', 'domain' => 'test');  
  •                 break;  
  •             case 'en_gb':  
  •                 $this->_options = array('lang' => 'en_US.UTF8', 'domain' => 'test');  
  •                 break;  
  •             default:  
  •                 $this->_options = array('lang' => 'zh_TW.UTF8', 'domain' => 'test');  
  •             break;  
  •         }  
  •   
  •         $this->setApplicationLocale();  
  •     }  
  •   
  •     /**
  •      * 设置应用程序语言包的参数,放在$this->_options中
  •      * @param mixed $options
  •      * @return void
  •      */  
  •     public function setOptions($options) {  
  •         if (!emptyempty($options)) {  
  •             foreach ($options as $key => $option) {  
  •                 $this->_options[$key] = $option;  
  •             }  
  •         }  
  •     }  
  •   
  •     /**
  •      * 设置应用程序语言包
  •      * @access public
  •      * @return void
  •      */  
  •     public function setApplicationLocale() {  
  •         putenv('LANG='.$this->_options['lang']);  
  •         putenv('LANGUAGE='.$this->_options['lang']);  
  •         setlocale(LC_ALL, $this->_options['lang']);  
  •         bindtextdomain($this->_options['domain'], PROJECTDIR.'/locale/');  
  •         textdomain($this->_options['domain']);  
  •         bind_textdomain_codeset($this->_options['domain'], 'UTF-8');  
  •     }  
  •   
  • }  
  •   
  • ?>  
  
  使用方法:
  

  • $lang = 'zh_TW';  
  • $locale = new Locale($lang);  
  
  
  

  
  
  根据上述提供的例子,再加上自己动手制作的经历,有以下笔记:
  
  1.我用的是Smarty-3.0.8 版本,上面这个&#8220;块函数&#8221;


$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>
<a href=&#8221;http://sourceforge.net/projects/smarty-gettext/&#8221;><{t}>点击下载插件<{/t}></a>
<a href=&#8221;http://sourceforge.net/projects/smarty-gettext/&#8221;><{t}>哈哈<{/t}></a>
<a href=&#8221;http://sourceforge.net/projects/smarty-gettext/&#8221;><{t}>哦哦<{/t}></a>
<a href=&#8221;http://sourceforge.net/projects/smarty-gettext/&#8221;><{t}>嘻嘻<{/t}></a>
<a href=&#8221;http://sourceforge.net/projects/smarty-gettext/&#8221;><{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
  把模板文件夹&#8220;\module\test\views\&#8221;内的所有的*.html文件生成default.c文件
3.把default.c文件生成default.mo文件
  xgettext -d default    default.c  --from-code=utf-8
4.编译default.mo文件
  msgfmt -o default.mo default.po
5.把default.po文件拷贝到 &#8220;locale/en_US/LC_MESSAGES/&#8221; 文件夹下  
  
  
  
  
  
  
  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-103717-1-1.html 上篇帖子: PHP的学习--PHP的引用 下篇帖子: 大话PHP缓存头
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表