百度翻译 接口使用实例

百度翻译接口类

trans_result) ? $text->trans_result : '';
        return isset($text[0]->dst) ? $text[0]->dst : '';
    }

    #获取目标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;
    }
}

实例1,(中文翻译英文)

# 定义需要翻译的内容
$title = '你好';

# 验证是否为汉字 ( 兼容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);
}

# 结果输出  Hello
echo $title;
exit;

实例2,(英文翻译中文)

# 定义需要翻译的内容
$title = 'Hello';

# 验证是否为汉字 ( 兼容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);
}

# 结果输出  您好
echo $title;
exit;

你可能感兴趣的:(百度,翻译,php)