This article mainly introduces the example of using Baidu translation api in php. For more information, see the PHP code of Baidu translation API.
The Code is as follows:
Function language ($ value, $ from = "auto", $ to = "auto ")
{
$ Value_code = urlencode ($ value );
# Urlencode the text to be translated
$ Appid = "YourApiKey ";
# The API Key you registered
$ Languageurl = "http://openapi.baidu.com/public/2.0/bmt/translate? Client_id = ". $ appid." & q = ". $ value_code." & from = ". $ from." & to = ". $;
# Generate the url get address of the translation API
$ Text = json_decode (language_text ($ languageurl ));
$ Text = $ text-> trans_result;
Return $ text [0]-> dst;
}
Function language_text ($ url) # obtain the content printed by the target URL
{
If (! Function_exists ('file _ get_contents ')){
$ File_contents = file_get_contents ($ url );
} Else {
$ Ch = curl_init ();
$ Timeout = 5;
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout );
$ File_contents = curl_exec ($ ch );
Curl_close ($ ch );
}
Return $ file_contents;
}
Echo language ('China ');
?>