In today’s global digital environment, multilingual content processing is crucial for websites and applications. Baidu Translate API is a powerful tool that supports translation between various languages. This guide demonstrates how to use PHP to call the Baidu Translate API to convert Chinese text into Italian.
First, register for a developer account on the Baidu Translate platform. After creating an application, you’ll receive an App ID, API Key, and Secret Key. These credentials are essential for accessing the API—keep them safe.
Download the official AipTranslate SDK and place it in your project directory (e.g., baidu_translate/). Then include it in your PHP script:
require_once 'baidu_translate/AipTranslate.php';
Set up the AipTranslate object using your credentials:
// Initialize AipTranslate object
$config = [
'appId' => 'your_app_id',
'apiKey' => 'your_api_key',
'secretKey' => 'your_secret_key',
];
$client = new AipTranslate($config);
Define the text to translate and the target language, then use the API to execute the translation:
// Text to translate
$text = '你好,世界';
// Target language (Italian)
$targetLanguage = 'it';
// Call the translation API
$result = $client->translate($text, 'auto', $targetLanguage);
Extract the translated text from the returned array:
// Get translated text
$translatedText = $result['trans_result'][0]['dst'];
// Output the result
echo $translatedText;
Here’s the full PHP example for translating Chinese to Italian using the Baidu API:
require_once 'baidu_translate/AipTranslate.php';
// Initialize
$config = [
'appId' => 'your_app_id',
'apiKey' => 'your_api_key',
'secretKey' => 'your_secret_key',
];
$client = new AipTranslate($config);
// Set translation parameters
$text = '你好,世界';
$targetLanguage = 'it';
// Call the translation API
$result = $client->translate($text, 'auto', $targetLanguage);
// Extract and display the result
$translatedText = $result['trans_result'][0]['dst'];
echo $translatedText;
By following the steps above, you can efficiently integrate Baidu Translate API into your PHP project to handle language conversion. The API supports a wide range of language pairs and is suitable for multilingual websites, cross-border e-commerce platforms, and content internationalization. Developers can extend and customize the interface to suit specific translation needs.