title: Google Translate API v2, v3 PHP
body: <p>I just started using the BING translate API to do a small volume of translations into most of their supported languages and that works pretty well.</p>
  
  <p>There is a GitHub project that has simple PHP code for making the API call to Microsoft.  You mostly just need the API key, and it can be customized pretty easily.</p>
  
  <p><a href="https://github.com/MicrosoftTranslator/Text-Translation-API-V3-PHP/blob/master/Translate.php" rel="nofollow noreferrer">Text-Translation-API-V3-PHP
  </a></p>
  
  <pre><code>// NOTE: Be sure to uncomment the following line in your php.ini file.
  // ;extension=php_openssl.dll
  // **********************************************
  // *** Update or verify the following values. ***
  // **********************************************
  // Replace the subscriptionKey string value with your valid subscription key.
  $key = 'ENTER KEY HERE';
  $host = "https://api.cognitive.microsofttranslator.com";
  $path = "/translate?api-version=3.0";
  
  // Translate to German and Italian.
  $params = "&amp;to=de&amp;to=it";
  $text = "Hello, world!";
  
  if (!function_exists('com_create_guid')) {
    function com_create_guid() {
      return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
          mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
          mt_rand( 0, 0xffff ),
          mt_rand( 0, 0x0fff ) | 0x4000,
          mt_rand( 0, 0x3fff ) | 0x8000,
          mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
      );
    }
  }
  
  function Translate ($host, $path, $key, $params, $content) {
      $headers = "Content-type: application/json\r\n" .
          "Content-length: " . strlen($content) . "\r\n" .
          "Ocp-Apim-Subscription-Key: $key\r\n" .
          "X-ClientTraceId: " . com_create_guid() . "\r\n";
      // NOTE: Use the key 'http' even if you are making an HTTPS request. See:
      // http://php.net/manual/en/function.stream-context-create.php
      $options = array (
          'http' =&gt; array (
              'header' =&gt; $headers,
              'method' =&gt; 'POST',
              'content' =&gt; $content
          )
      );
      $context  = stream_context_create ($options);
      $result = file_get_contents ($host . $path . $params, false, $context);
      return $result;
  }
  
  $requestBody = array (
      array (
          'Text' =&gt; $text,
      ),
  );
  $content = json_encode($requestBody);
  $result = Translate ($host, $path, $key, $params, $content);
  // Note: We convert result, which is JSON, to and from an object so we can pretty-print it.
  // We want to avoid escaping any Unicode characters that result contains. See:
  // http://php.net/manual/en/function.json-encode.php
  $json = json_encode(json_decode($result), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
  echo $json;
  </code></pre>
  
  <p>I also have a Google Cloud account and am looking for something similar for a few languages that Google supports that BING does not.  For v2, it is not too hard to call Google to make the return the translations.</p>
  
  <p>I found this GitHub project that seems to work for v2 API calls with an API key, but unfortunately I think that is a fee-for-service program now ?</p>
  
  <p><a href="https://github.com/googleapis/google-cloud-php-translate" rel="nofollow noreferrer">google-cloud-php-translate
  </a></p>
  
  <p>That also seems to work pretty well if you have an API key.  If you are using v3, they apparently updated the libraries and support.  You can make a CURL call from the command line and they have some of that documented on their website, but I am looking for a way to make the call using a PHP file.</p>
  
  <pre><code>require 'vendor/autoload.php';   
  use Google\Cloud\Translate\TranslateClient;
  
  $translate = new TranslateClient([
      'key' =&gt; 'APIKEY'
  ]);
  
  // Translate text from english to french.
  $result = $translate-&gt;translate('Hello world!', [
      'target' =&gt; 'fr'
  ]);
  
  echo $result['text'] . "\n";
  
  // Detect the language of a string.
  $result = $translate-&gt;detectLanguage('Greetings from Michigan!');
  
  echo $result['languageCode'] . "\n";
  
  // Get the languages supported for translation specifically for your target language.
  $languages = $translate-&gt;localizedLanguages([
      'target' =&gt; 'en'
  ]);
  
  foreach ($languages as $language) {
      echo $language['name'] . "\n";
      echo $language['code'] . "\n";
  }
  
  // Get all languages supported for translation.
  $languages = $translate-&gt;languages();
  
  foreach ($languages as $language) {
      echo $language . "\n";
  }
  </code></pre>
  
  <p>Not sure that is even possible, but the best I can come up with is something like this based upon the command line CURL, but the authentication is wrong and fails.  I do have the .json file for my Project/Service credentials.  The ${PROJECT_ID} I presume is the project ID for the account, and Bearer $(gcloud auth application-default print-access-token) I am not sure about.  There are some instructions about how to obtain that through the CLI, but is there a way to get that via a PHP file ?  Like I say, the v2 version works fine.</p>
  
  <pre><code>$ch = curl_init();   
  curl_setopt($ch, CURLOPT_URL, "https://translation.googleapis.com/v3beta1/projects/${PROJECT_ID}/locations/global:detectLanguage");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n     mimeType: 'text/plain',\n     content: 'Omnia Gallia est divisa in tres partes'\n}");
  curl_setopt($ch, CURLOPT_POST, 1);
  
  $headers = array();
  $headers[] = 'Authorization: Bearer $(gcloud auth application-default print-access-token)';
  $headers[] = 'Content-Type: application/json';
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  
  $result = curl_exec($ch);
  if (curl_errno($ch)) {
      echo 'Error:' . curl_error($ch);
  } else {
      echo $result;
  }
  curl_close ($ch);
  </code></pre>
  
  <p>There might be clues here, but it talks about exporting the path for the credentials file and running PHP scripts from the command line instead of from a server.</p>
  
  <p><a href="https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/translate/" rel="nofollow noreferrer">Google Cloud Translate API Samples</a></p>