How to realize the translation function from Portuguese to Japanese through PHP Baidu Translation API?
Introduction:
With the development of globalization today, language translation has become an important need. In development, we often need to implement language translation functions through API interfaces. This article will demonstrate how to implement the translation function from Portuguese to Japanese through the PHP Baidu Translation API.
Prerequisites:
Before we start, we need to ensure that the following conditions have been met:
Steps:
<?php require_once('vendor/autoload.php'); use StichozaGoogleTranslateTranslateClient;
Here we use a third-party library "StichozaGoogleTranslate" to implement the translation function. In actual development, you can also use other translation libraries.
define('API_KEY', 'YOUR_API_KEY'); define('SECRET_KEY', 'YOUR_SECRET_KEY');
Replace "YOUR_API_KEY" and "YOUR_SECRET_KEY" with your API Key and Secret Key.
function translate($text, $from, $to) { $appId = API_KEY; $appSecret = SECRET_KEY; $httpClient = new GuzzleHttpClient(); // 获取API Token $response = $httpClient->get('https://openapi.baidu.com/oauth/2.0/token', [ 'query' => [ 'grant_type' => 'client_credentials', 'client_id' => $appId, 'client_secret' => $appSecret, ], ]); $result = json_decode((string) $response->getBody(), true); $accessToken = $result['access_token']; // 翻译文本 $response = $httpClient->get('https://fanyi-api.baidu.com/api/trans/vip/translate', [ 'query' => [ 'q' => $text, 'from' => $from, 'to' => $to, 'appid' => $appId, 'salt' => rand(10000,99999), 'sign' => md5($appId . $text . rand(10000,99999) . $appSecret), ], 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded', ], ]); $result = json_decode((string) $response->getBody(), true); return $result['trans_result'][0]['dst']; } $text = "Olá, mundo!"; //需要翻译的葡萄牙语文本 $translated_text = translate($text, 'pt', 'jp'); //将葡萄牙语翻译为日语 echo "翻译结果: " . $translated_text;
In this code, we define a function named "translate", which accepts three parameters: required Translated text, source language and target language. We first obtain the API Token through the API Key and Secret Key, and then use the Token to translate the text. Finally, we print the translation results to the screen.
php translation.php
You will see in the command line to the following output:
翻译结果: こんにちは、世界!
This indicates that we successfully translated Portuguese to Japanese.
Conclusion:
Through the above steps, we successfully implemented the translation function from Portuguese to Japanese through the PHP Baidu Translation API. Hope this article helps you! If you have any questions please feel free to leave a message.
The above is the detailed content of How to implement Portuguese to Japanese translation function through PHP Baidu Translation API?. For more information, please follow other related articles on the PHP Chinese website!