Baidu translation interface class
- /**
- * Baidu Developer Center: http://developer.baidu.com/
- * Baidu Translation API: http://developer.baidu.com/wiki/index.php?title=docs
- */
- class baiduAPI{
- /**
- * $from : Source language: language
- * $to : Target language: language code or auto
- */
- static public function fanyi($value, $from="auto" , $to="auto")
- {
- $value_code=urlencode($value);
- #First perform urlencode processing on the text to be translated
- $appid="Ow83extUdl2zLm94s7ldkw5D";
- #Your registered API Key
- $languageurl = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=" . $appid ."&q=" .$value_code. "&from=".$from."&to=".$to;
- #Generate the URL GET address of the translation API
- $text=json_decode(self::language_text($languageurl));
- $text = isset($text->trans_result) ? $text->trans_result : '';
- return isset($text[0]->dst) ? $text[0]->dst : '';
- }
-
- #Get the content printed by the target URL
- static function language_text($url)
- {
- if(!function_exists('file_get_contents')) {
- $file_contents = file_get_contents($url);
- } else {
- $ch = curl_init();
- $timeout = 5;
- curl_setopt ($ch, CURLOPT_URL, $url) ;
- curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
- $file_contents = curl_exec($ch);
- curl_close($ch);
- }
- return $file_contents;
- }
- }
Copy code
Example 1, (Chinese to English)
- # Define the content that needs to be translated
- $title = 'Hello';
-
- # Verify whether it is Chinese characters (compatible with gb2312, utf-8 )
- if (preg_match("/[x7f-xff]/", $title)) {
- $title = baiduAPI::fanyi($title, $from="zh", $to="en");
- } else {
- $title = baiduAPI::fanyi($title, $from="en", $to="zh");
- $title = iconv('utf-8', 'gbk', $title);
- }
-
- # Result output Hello
- echo $title;
- exit;
Copy code
Example 2, (English to Chinese)
- # Define the content that needs to be translated
- $title = 'Hello';
-
- # Verify whether it is Chinese characters (compatible with gb2312, utf-8)
- if (preg_match("/[x7f-xff]/", $title)) {
- $title = baiduAPI::fanyi($title, $from="zh ", $to="en");
- } else {
- $title = baiduAPI::fanyi($title, $from="en", $to="zh");
- $title = iconv('utf- 8', 'gbk', $title);
- }
-
- # Result output Hello
- echo $title;
- exit;
Copy code
|