With the growth of globalization and increasing international communication, the demand for language translation has also risen. As a developer, you can utilize various translation APIs to implement translation features. This article will explain how to use the PHP Baidu Translation API to implement translation from Italian to Korean and share some translation tips.
First, you need to create an application on the Baidu Translation Open Platform and obtain an API Key and Secret Key. These credentials will be used in your PHP code.
Before starting development, make sure that you have installed the cURL and JSON extensions. These two extensions are essential for using the Baidu Translation API.
Below is an example of PHP code to implement translation from Italian to Korean:
<?php // Define API Key and Secret Key define('API_KEY', 'Your API Key'); define('SECRET_KEY', 'Your Secret Key'); // Define source and target languages $from = 'it'; $to = 'ko'; // Define text to be translated $text = 'Ciao, come stai?'; // Generate the sign parameter $salt = rand(10000, 99999); $sign = md5(API_KEY . $text . $salt . SECRET_KEY); // Send HTTP request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://api.fanyi.baidu.com/api/trans/vip/translate'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'q' => $text, 'from' => $from, 'to' => $to, 'appid' => API_KEY, 'salt' => $salt, 'sign' => $sign )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); // Parse the JSON response $result = json_decode($response, true); // Get the translation result $translation = $result['trans_result'][0]['dst']; // Output the translation echo $translation; ?>
In the code above, we first define the API Key and Secret Key. Then, we specify the source language as Italian ('it') and the target language as Korean ('ko'). Next, we define the text to be translated (e.g., 'Ciao, come stai?'). We use the rand(10000, 99999) function to generate a random number as the salt parameter and use the md5 function to generate the sign parameter. Finally, we use cURL to send an HTTP request to the Baidu Translation API, parse the JSON response, and retrieve the translation result.
$texts = array('Ciao', 'come', 'stai'); foreach ($texts as $text) { // Translation code here }
$translation = $result['trans_result'][0]['dst']; $translation = iconv('UTF-8', 'GBK', $translation);
$error_code = $result['error_code']; $error_msg = $result['error_msg']; if ($error_code != 0) { echo "Error code: $error_code"; echo "Error message: $error_msg"; }
This article explained how to use the PHP Baidu Translation API to implement translation from Italian to Korean. We first registered for the Baidu Translation API, installed the necessary PHP extensions, then wrote the PHP code to perform the translation, and shared some translation tips. We hope this article will help you easily implement multilingual translation features.