Home > Article > Backend Development > Use PHP to write an example tutorial for docking Baidu Machine Translation API
Using PHP to write an example tutorial for docking Baidu Machine Translation API
Introduction:
As people's demand for language communication continues to increase, machine translation technology has gradually become Today's hot technologies. The Baidu Machine Translation API provides developers with an easy way to integrate machine translation functions into their own applications. This article will introduce how to use PHP to write an example tutorial for docking Baidu Machine Translation API, and attach corresponding code examples.
<?php class BaiduTranslationAPI { private $api_key; private $secret_key; public function __construct($api_key, $secret_key) { $this->api_key = $api_key; $this->secret_key = $secret_key; } public function translate($text, $from = 'auto', $to = 'auto') { $url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'; $salt = rand(10000, 99999); $sign = md5($this->api_key . $text . $salt . $this->secret_key); $params = [ 'q' => $text, 'from' => $from, 'to' => $to, 'appid' => $this->api_key, 'salt' => $salt, 'sign' => $sign ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); $result = json_decode($response, true); return $result['trans_result'][0]['dst']; } } ?>
<?php require_once 'BaiduTranslationAPI.php'; $api_key = '你的API Key'; $secret_key = '你的Secret Key'; $translator = new BaiduTranslationAPI($api_key, $secret_key); $text = 'Hello, World!'; $source_language = 'en'; $target_language = 'zh'; $translated_text = $translator->translate($text, $source_language, $target_language); echo "原文:" . $text . " "; echo "译文:" . $translated_text . " "; ?>
The above code will output the original text and translation, and print the result.
Conclusion:
Through the introduction of this article, you have learned how to use PHP to write an example tutorial for docking Baidu Machine Translation API. You can call different Baidu machine translation API interfaces according to your own needs to achieve more functions. I hope this tutorial can help you successfully integrate Baidu Machine Translation API into your application.
The above is the detailed content of Use PHP to write an example tutorial for docking Baidu Machine Translation API. For more information, please follow other related articles on the PHP Chinese website!