With the acceleration of globalization, language communication has become increasingly important. Translation tools have also become more widely used. Baidu Translation API is a powerful tool that supports translation for multiple languages. This article will introduce how to use the PHP Baidu Translation API to implement a translation function from Spanish to Russian.
First, you need to visit the Baidu Translation Open Platform, register and log in to your account, and create a new application. You can obtain your App ID and key on the application management page.
Before implementing the translation function, you need to set up a PHP development environment. You can use tools like XAMPP or WAMP for this purpose.
Create a PHP file named translate.php. Here's an example of the code:
<?php // Set the request URL and parameters $url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'; $appid = 'your_appid'; // Replace with your own App ID $key = 'your_key'; // Replace with your own key // Get the text to be translated and the target language $q = $_POST['text']; // The text to be translated $from = 'es'; // Source language is Spanish $to = 'ru'; // Target language is Russian // Generate the signature according to Baidu Translation API's requirements $salt = rand(10000,99999); $sign = md5($appid . $q . $salt . $key); // Send a POST request to Baidu Translation API $postData = array( 'q' => $q, 'from' => $from, 'to' => $to, 'appid' => $appid, '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($postData)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); // Parse the response from Baidu Translation API $result = json_decode($response, true); // Output the translation result echo $result['trans_result'][0]['dst']; ?>
Next, create an HTML file named index.html. Here's an example of the HTML code:
<input type="submit" value="Translate">
</form>