近日在开发一个新的项目,要将采集来的数据翻译成多国语言。这个项目将会被作为DEDE的一个扩展模块免费发布。敬请期待!
这里使用到了Google的AJAX Translate API(注:虽然Google没有提供PHP版本的API,但我们一样可以使用基于HTTP协 议的AjaxAPI)和Snoopy类。
如果要给项目命名的话,可以称为 Google Translate API For PHP
今日先放出这个PHPTranslate类,使用方法见以下Demo:
1 | $Google = new GoogleTranslate(); |
2 | $Google->translate('这是一个基于 Google在线翻译的工具'); |
以下列出本类的代码。
018 | var $text = '这是一个基于Google在线翻译的工具!'; |
024 | function GoogleTranslate($text, $from, $to) |
026 | $this->__construct($text, $from, $to); |
030 | function __construct($text='', $from='', $to='') |
032 | $snoopy = 'Snoopy.class.php'; |
033 | if (is_file($snoopy)) |
035 | require_once $snoopy; |
036 | $this->snoopy = new Snoopy(); |
037 | $this->snoopy->agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.8) Gecko/20100202 Firefox/3.5.8'; |
038 | $this->snoopy->accept= 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'; |
040 | $this->snoopy->rawheaders['Accept-Language'] = 'zh-cn,zh;q=0.5'; |
042 | echo "file '$snoopy' do not exists!"; |
046 | $text && $this->text = $text; |
047 | $from && $this->from = $from; |
048 | $to && $this->to = $to; |
050 | $this->text && $this->translate($this->text, $this->from, $this->to); |
055 | $Lang = array("中文(繁体)"=>"zh-TW", "中文(简体)"=>"zh-CN", "阿尔巴尼亚语"=>"sq", "阿拉伯语"=>"ar", "爱尔兰语"=>"ga", "爱沙尼亚语"=>"et", "白俄罗斯语"=>"be", "保加利亚语"=>"bg", "冰岛语"=>"is", "波兰语"=>"pl", "波斯语"=>"fa", "布尔文(南非荷兰语)"=>"af", "丹麦语"=>"da", "德语"=>"de", "俄语"=>"ru", "法语"=>"fr", "菲律宾语"=>"tl", "芬兰语"=>"fi", "海地克里奥尔语 ALPHA"=>"ht", "韩语"=>"ko", "荷兰语"=>"nl", "加利西亚语"=>"gl", "加泰罗尼亚语"=>"ca", "捷克语"=>"cs", "克罗地亚语"=>"hr", "拉脱维亚语"=>"lv", "立陶宛语"=>"lt", "罗马尼亚语"=>"ro", "马耳他语"=>"mt", "马来语"=>"ms", "马其顿语"=>"mk", "挪威语"=>"no", "葡萄牙语"=>"pt", "日语"=>"ja", "瑞典语"=>"sv", "塞尔维亚语"=>"sr", "斯洛伐克语"=>"sk", "斯洛文尼亚语"=>"sl", "斯瓦希里语"=>"sw", "泰语"=>"th", "土耳其语"=>"tr", "威尔士语"=>"cy", "乌克兰语"=>"uk", "西班牙语"=>"es", "希伯来语"=>"iw", "希腊语"=>"el", "匈牙利语"=>"hu", "意大利语"=>"it", "意第绪语"=>"yi", "印地语"=>"hi", "印尼语"=>"id", "英语"=>"en", "越南语"=>"vi"); |
056 | if(!in_array($this->from, $Lang)) |
060 | }elseif(!in_array($this->to, $Lang)) |
062 | echo '尚不支持您要翻译的目标语种!'; |
066 | function translate($text='', $from='', $to='') |
068 | $text && $this->text = $text; |
069 | $from && $this->from = $from; |
070 | $to && $this->to = $to; |
074 | $vars['client'] = 't'; |
075 | $vars['hl'] = 'zh-CN'; |
078 | $vars['sl'] = $this->from; |
079 | $vars['tl'] = $this->to; |
080 | $vars['text'] = $text; |
084 | $this->result = NULL; |
087 | $this->snoopy->submit($this->GoogleURL, $vars); |
088 | $this->json = $this->snoopy->results; |
094 | $result = json_decode($this->json); |
095 | $this->result = $this->trans = NULL; |
096 | if(@is_object($result->dict[0])) |
098 | $this->dict = $result->dict[0]; |
100 | if(@is_object($result->sentences[0])) |
102 | $this->result = $this->trans = $result->sentences[0]->trans; |
103 | }else return $this->result = $this->trans; |
108 | $Google = new GoogleTranslate(); |
109 | $Google->translate('这是一个基于 Google在线翻译的工具'); |
没有评论:
发表评论