Skip to content

Instantly share code, notes, and snippets.

@heristop
Last active July 1, 2016 06:40
Show Gist options
  • Save heristop/dc701f7c62fcf52041c2 to your computer and use it in GitHub Desktop.
Save heristop/dc701f7c62fcf52041c2 to your computer and use it in GitHub Desktop.
Use Google Translate API through YQL
<?php
trait autoTranslate
{
protected
$lang1,
$lang2
;
protected function translate($text)
{
if ($text == "") return "";
$translatedText = iconv('UTF-8', 'US-ASCII//TRANSLIT', $text);
$url = "http://query.yahooapis.com/v1/public/yql";
$query = rawurlencode("select * from google.translate where q=\"{$translatedText}\" and source=\"{$this->lang1}\" and target=\"{$this->lang2}\";");
$return = $this->get("{$url}?q=$query&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
$results = json_decode($return);
if (is_array($results->query->results->json->sentences)) {
$translationArray = array();
foreach ($results->query->results->json->sentences as $sentence) {
$translationArray[] = $sentence->trans;
}
$translatedText = implode("", $translationArray);
} else {
$translatedText = $results->query->results->json->sentences->trans;
}
if ($translatedText == "") return $text;
return $translatedText;
}
protected function get($url, array $options = array())
{
$defaults = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if(! $result = curl_exec($ch)) {
trigger_error(curl_error($ch));
}
curl_close($ch);
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment