With globalization advancing, language barriers have become a major challenge for cross-border communication, increasing the demand for translation tools. Baidu Translate, a free online translation service, supports text, webpage, and voice translation for over 100 languages. By leveraging PHP, a widely used server-side scripting language, we can implement automatic mutual translation between Chinese and French to improve cross-language communication efficiency.
Before using Baidu Translate API, you need to create an application and obtain an API key from Baidu Translate's developer platform.
$api_url = "http://api.fanyi.baidu.com/api/trans/vip/translate"; // API endpoint URL
$api_appid = "Your API ID"; // Application ID
$api_secret = "Your Secret Key"; // Security key
$from_lang = "fr"; // Source language
$to_lang = "zh"; // Target language
In the above code, we define the API endpoint URL, application ID, and secret key, and set the source language to French and the target language to Chinese.
Create a PHP function that uses the curl library to send POST requests to the Baidu Translate API and parses the response into an array for easy processing.
function curl_request($url, $params = array()){
$ch = curl_init(); // Initialize curl
curl_setopt($ch, CURLOPT_URL, $url); // Set URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Return response instead of outputting directly
curl_setopt($ch, CURLOPT_POST, 1); // Use POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, $params); // POST parameters
$response = curl_exec($ch); // Execute request
curl_close($ch); // Close curl
return json_decode($response, true); // Decode JSON to array
}
This function initializes curl, sets the URL and parameters, sends the POST request, and returns the decoded JSON response as an array.
Using the above function, we can easily implement mutual translation between Chinese and French. Example code is as follows:
$text = "Bonjour le monde!"; // Text to translate
$params = array(
"q" => $text,
"from" => $from_lang,
"to" => $to_lang,
"appid" => $api_appid,
"salt" => rand(10000, 99999),
"sign" => ""
); // Assemble POST parameters
$params['sign'] = md5($api_appid . $text . $params['salt'] . $api_secret); // Calculate signature
$result = curl_request($api_url, $params); // Send request
$translation = $result["trans_result"][0]["dst"]; // Extract translation result
In the code, we first define the text to translate and POST parameters, then calculate the MD5 signature for security, send the request using curl_request, and finally extract the translated text from the response.
This article explained how to use PHP to implement bidirectional translation between Chinese and French by calling the Baidu Translate API. It covered the process of applying for an API key, constructing and sending POST requests, and parsing the results. This approach enables developers to integrate efficient and reliable Chinese-French translation capabilities, enhancing cross-language applications.