Monday, February 3, 2020

How to integrate google Translate Api using PHP?

Read carefully follow below steps before you integrate the google cloud API for translate using PHP.


Step:1 -> Download the Google client direct from git repo :

   //command line download using below command
           $ composer require google/cloud-translate

Step: 2-> Creating a Service Account for Authentication and get an API_KEY

Step:3 -> Create a new file classTGooleranslate.php 

class googleTranslateMode{
          require vendor/autoload.php;
          use Google\Cloud\Translate\TranslateClient;

 //Google Trans
   public static function goolgeTransConnect() {
      if(!isset(self::$goolgeObj)) {    
          self::$goolgeObj = new TranslateClient(['key' => GOOGLE_TRANSLATE_KEY]);
      }
      return self::$goolgeObj;
     }


       //Convert translate from Google APi to Target Language
 public function doCaptiontranslate(){
  
 try {    
        $translate      =   self::goolgeTransConnect();
  //english  to translate spanish   
  $lang      =  'es'; 
  
  $result     = array();
  $content ="Translate english to spanish";
  
  if(!empty(trim($content)) && !empty($lang)){
   $result    =   $this->curlTranslateurl($lang,$content,$translate);
  $translatedContent   = $result['text'];
  return  $translatedContent;

     }catch (Exception $e) {
   echo "<pre>";print_r($e);die;
     }
 }

        
 #@ Function    : curlTranslateurl
 #@ Description   : Get language Translated content from google
 public function curlTranslateurl($lang=null,$content=null,$translate,$response=true){
  try{
   $result=array();
   if(!empty($lang) && !empty($content)){
    if($response){
     $result = $translate->translate($content, ['target' => $lang]);  
    }    
   }
   return $result;
  }catch (Exception $e) { 
   
   
   return $e;
  }
 }
    }

Create  an instance of the googleTranslateMode class
$tansObj=new googleTranslateMode();
$tansObj->doCaptiontranslate();
OutPut : Traducir inglés a español

No comments:

Post a Comment