PHP多国语言开发:CodeIgniter 2PHP框架中的多国语言,语言包(i18n)多国语言库
我们在CodeIgniter开发中经常会碰到多国语言网站,这里我们就来介绍一种简单有效的多国语言的操作方法。
语言在地址中是这样的:
cit.cn/en/about
cit.cn/zh/about
保持使用库:Language Class
视图中
=lang('about.gender')?>
英文语言文件
$lang['about.gender'] = "I'm a man";
英文语言文件
$lang['about.gender'] = "I'm a man";
中文语言文件
$lang['about.gender'] = "我是男人";
cit.cn/en/about显示的结果
I'm a man
cit.cn/zh/about显示的结果
我是男人
下载ci_i18n_library.zip
将MY_Lang.php 和 MY_Config.php 放到 application/core
在 application/config/routes.php 增加
// example: '/en/about' -> use controller 'about'
$route['^fr/(.+)$'] = "$1";
$route['^zh/(.+)$'] = "$1";
// '/en' and '/zh' -> use default controller
$route['^fr$'] = $route['default_controller'];
$route['^zh$'] = $route['default_controller'];
让我们创建一个中英双语的页面
application/language/english/about_lang.php
application/language/chinese/about_lang.php
application/controllers/about.php
load->helper('language');
$this->load->helper('url');
// load language file
$this->lang->load('about');
$this->load->view('about');
}
}
/* End of file */
application/views/about.php
=lang('about.gender')?>
=anchor('music','Shania Twain')?>
http://your_base_url/en/about
I'm a man
http://your_base_url/en/about
我是男人
你需要去翻译CodeIgniter里面system/language语言文件,例子:如果你需要使用“Form Validation”库,你就需要翻译:
system/language/form_validation_lang.php 到
application/language/chinese/form_validation_lang.php.
页面链接将会添加上当前语言的目录,但是文件链接不会。可以参考:www.cnmeizhuang.com
site_url('about/my_work');
// http://mywebsite.com/en/about/my_work
site_url('css/styles.css');
// http://mywebsite.com/css/styles.css
获取当前语言
$this->lang->lang();
// en
切换到另一个语言
anchor($this->lang->switch_uri('zh'),'Display current page in chinese');
//the root page (/) is supposed to be some kind of splash page, without any specific //language. This can be changed: see “No splash page” below.
MY_Config.php保函一个重写的site_url():当生成语言地址目录的时候增加语言段,同样适用于anchor(), form_open()...
一个特殊地址不需要保函语言文件,默认的根目录地址(/)就是一特殊的URI.例如:www.nongyejingc.com /
你需要其他的特殊URIs,例如管理后台目录admin只需要一个语言文件。
在application/core/MY_Lang.php增加admin到数组$special中,现在链接到admin的链接就不会加入当前语言包路径了。
site_url('admin');
// http://mywebsite.com/admin
在application/core/MY_Lang.php
1. 删除从$special数组删除“”;
2. 设置$default_uri,例如home
3. 如果你的默认语言是english的话,现在连接到/的请求,被重定向到en/home
4. 默认语言是$languages数组的第一个项目;
1. 在application/core/MY_Lang.php文件中的$languages数组增加新的语言:
// example: German (de)
'de' => 'german',
2. application/config/routes.php:增加新的路由
// example: German (de)
$route['^de/(.+)$'] = "$1";
$route['^de$'] = $route['default_controller'];
3. 在application/language目录中增加语言文件夹,这里的例子是“German”,需要命名为german。
以上就是CI框架 利用语言包(i18n)库,php多国语言实现的一些思路。