forked from WillSkates/GoogleTranslator-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoogleTranslator.class.php
More file actions
77 lines (61 loc) · 1.54 KB
/
GoogleTranslator.class.php
File metadata and controls
77 lines (61 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
/**
* GoogleTranslator for PHP - library for translating text via Google Translator API.
*
* @author David Grudl
* @copyright Copyright (c) 2010 David Grudl
* @license New BSD License
* @link http://phpfashion.com/
* @version 1.0
*/
class GoogleTranslator
{
/** @var string source lang */
private $srcLang;
/** @var string destination lang */
private $destLang;
/**
* @param string source language (optional)
* @param string destination language
*/
public function __construct($srcLang, $destLang)
{
$this->srcLang = $srcLang;
$this->destLang = $destLang;
}
/**
* Translates text.
* @param string
* @return string
* @throws GoogleTranslatorException
*/
public function translate($text)
{
$options = array(
'http' => array(
'method' => 'POST',
'timeout' => 20,
'content' => http_build_query(array(
'v' => '1.0',
'langpair' => "$this->srcLang|$this->destLang",
'q' => (string) $text
), '', '&'),
),
);
$f = @fopen('http://ajax.googleapis.com/ajax/services/language/translate', 'r', FALSE, stream_context_create($options));
if (!$f) {
throw new GoogleTranslatorException('Server error');
}
$json = @json_decode(stream_get_contents($f)); // intentionally @
if (!isset($json->responseData->translatedText)) {
throw new GoogleTranslatorException('Invalid server response');
}
return $json->responseData->translatedText;
}
}
/**
* An exception generated by GoogleTranslator.
*/
class GoogleTranslatorException extends Exception
{
}