PHP implements translation function

       Today we will talk about using PHP to achieve translation function . Of course, PHP cannot be a translator. We need to use special translation services.

The program of the event gives us an open API interface to obtain data, and finally hand it over to PHP to parse the data and display it on the platform we need.

       Everyone should know Youdao Translation. It is a relatively good translation platform in China. Today we will use its open interface to learn. Let's start

Explain the code.

       <?php
          function transLate($word){

               // keyfrom and apikey are provided by Youdao open platform

               // You can get it by registering here: http://fanyi.youdao.com/openapi
       $keyfrom = "******";
       $apikey = "******";     

                 
       // Display the passed value by translating json format
       $url_youdao = 'http://fanyi.youdao.com/fanyiapi.do?keyfrom='.$keyfrom.'&key='.$apikey.'&type=data&doctype=json&version=1.1&q='.$word;


               // Use the functions that come with PHP to grab the json data returned by the URL
       $json = file_get_contents($url_youdao);


      // Description: If it is written as $obj = json_decode($json,true);
              // Then obj is an array at this time
              . object.

      $obj = json_decode($json);
        

              // get return code 
      $errorCode = $obj->errorCode;      


 if(isset($errorCode))
 {
switch ($errorCode) 
{
case 0:         // Indicates that the returned data is normal 
$trans = $obj->translation[0];     
break;


case 20:
$trans = 'The text to translate is too long';
break;


case 30:
$trans = 'Cannot do valid translation';
break;


case 40:
$trans = 'Unsupported language type';
break;


   case 50:
$trans = 'Invalid key';
break;

default:
$trans = 'An exception occurred';
break;
}

  }
  return $trans;
}

        // Test "English to Chinese" or "Chinese to English" can be tested
echo transLate('Nice to meet you');
echo transLate('Nice to meet you');
?>

         In fact, there are still many cases of using PHP to parse open API interfaces to obtain data, and I will share them with you in the future!

         大家可以关注我的微信公众号:iwork,我会每天推送一篇原创文章,让大家都能有所收获!



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325370293&siteId=291194637