Main content (diversen)

Cover image
Main content of the site. All will soon be moved into the blog section.

simple google translation class for php



0 Comments

Note: For a up to date version of this script use: https://github.com/diversen/simple-php-classes/blob/master/diversen/gtranslate.php

Very simple class for doing translation with google. Usage:

Get a list of language codes support by the google api

 
include_once "GTranslate.php";
// get language translatable languages for a source language
$g_options = array();
$g_options['target'] = "en";
$g_options['key'] = 'your_google_api_key';
gTranslate::setOptions($g_options);
$ary = GTranslate::getSupportLangs();
print_r($ary);
 

translate a string into a language:

 
include_once "GTranslate.php";
 
$g_options = array();
$g_options['key'] = 'your_google_api_key';
// english
$g_options['source'] = 'en';
// to chinese
$g_options['target'] = 'zh';
gTranslate::setOptions($g_options);
$trans = GTranslate::translateSingle("Hello World");
// write out translation of hello world
echo $trans;
 

The class:

 
<?php
 
class GTranslate {
    public static $options;
 
    const GTranslate_URL = 'https://www.googleapis.com/language/translate/v2';
 
    public static function setOptions ($options) {
        self::$options = $options;
    }
 
    public static function getSupportLangs (){
        $url = self::GTranslate_URL . "/languages?";
        $url.= "key=" . self::$options['key'] . "&";
        $url.= "target=" . self::$options['target'];
        $str = file_get_contents($url);
        $ary = json_decode($str, true);
        return $ary;
    }
 
    public static function translateString ($str) {
        $url = self::GTranslate_URL . "?";
        $url.= "key=" . self::$options['key'] . "&";
        $url.= "target=" . self::$options['target'] . "&";
        $url.= "source=" . self::$options['source'] . "&";
        $url.= "q=" . urlencode($str);
        $str = file_get_contents($url);
        $ary = json_decode($str, true);
        return $ary;
    }
 
    public static function translateSingle ($str) {
        $ary = self::translateString($str);
        if (isset($ary['data']['translations'][0]['translatedText'])){
            return $ary['data']['translations'][0]['translatedText'];
        }
        return null;
    }
}
 

Share a link to this entry via email, Google+, Twitter, Facebook.
This page has been viewed 1536 times. First hit: 25-Mar-2013 22:24:39

Comments