stichoza / google-translate-php Goto Github PK
View Code? Open in Web Editor NEW🔤 Free Google Translate API PHP Package. Translates totally free of charge.
License: MIT License
🔤 Free Google Translate API PHP Package. Translates totally free of charge.
License: MIT License
An exception is thrown when trying to generate a translation from a string or array.
On line 298 of the translate client, it seems to loop over a non-existent array:
foreach ($responseArrayForLanguages as $itemArray) {
// $itemArray is actually a string.
foreach ($itemArray as $item) {
if (is_string($item)) {
$detectedLanguages[] = $item;
}
}
}
In the url parameters you can specify multiple text
strings (or q
it's the same) so that instead of splitting a long string into substrings and call each time a translation, call it only once with the array of substrings.
Ignore this comment :)
Hello, I have tried this:
include ('GoogleTranslate.php');
$tr = new GoogleTranslate("en", "de");
echo $tr->translate("Hello World!");
And I got two Errors and the translated text:
Warning: tempnam() [function.tempnam]: open_basedir restriction in effect. File(/tmp) is not within the allowed path(s): (/home/.sites/117/site3029/web:/home/.sites/117/site3029/tmp:/usr/share/pear) in /home/.sites/117/site3029/web/GoogleTranslate.php on line 87
Warning: unlink() [function.unlink]: open_basedir restriction in effect. File() is not within the allowed path(s): (/home/.sites/117/site3029/web:/home/.sites/117/site3029/tmp:/usr/share/pear) in /home/.sites/117/site3029/web/GoogleTranslate.php on line 95
Hallo Welt !
Can you tell me what is my mistake?
Till yesterday everything was working perfectly with your translator, but today I'm getting the next error:
Fatal error: Uncaught exception 'ErrorException' with message 'Client error response [url] http://translate.google.com/translate_a/t [status code] 403 [reason phrase] Forbidden'
And the stack trace says that comes from lines 215, 247 and 143 of the method TranslateClient.php.
Do you suspect which is the problem?
Only first sentence is returned from translated text.
./vendor/bin/phpunit
PHPUnit 4.8.24 by Sebastian Bergmann and contributors.
......EEEEEEE.
Time: 2.93 seconds, Memory: 6.00Mb
There were 7 errors:
1) Stichoza\GoogleTranslate\Tests\LanguageDetectionTest::testSingleWord
ErrorException: Client error: `POST http://translate.google.com/translate_a/t` resulted in a `403 Forbidden` response:
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, w (truncated...)
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:262
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:299
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:175
/home/limon/www/google-translate-php/tests/LanguageDetectionTest.php:16
2) Stichoza\GoogleTranslate\Tests\LanguageDetectionTest::testSingleSentence
ErrorException: Client error: `POST http://translate.google.com/translate_a/t` resulted in a `403 Forbidden` response:
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, w (truncated...)
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:262
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:299
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:175
/home/limon/www/google-translate-php/tests/LanguageDetectionTest.php:25
3) Stichoza\GoogleTranslate\Tests\LanguageDetectionTest::testMultipleSentence
ErrorException: Client error: `POST http://translate.google.com/translate_a/t` resulted in a `403 Forbidden` response:
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, w (truncated...)
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:262
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:299
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:175
/home/limon/www/google-translate-php/tests/LanguageDetectionTest.php:34
4) Stichoza\GoogleTranslate\Tests\LanguageDetectionTest::testStaticAndNonstaticDetection
ErrorException: Client error: `POST http://translate.google.com/translate_a/t` resulted in a `403 Forbidden` response:
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, w (truncated...)
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:262
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:299
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:175
/home/limon/www/google-translate-php/tests/LanguageDetectionTest.php:43
5) Stichoza\GoogleTranslate\Tests\TranslationTest::testTranslationEquality
ErrorException: Client error: `POST http://translate.google.com/translate_a/t` resulted in a `403 Forbidden` response:
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, w (truncated...)
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:262
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:299
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:175
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:395
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:145
/home/limon/www/google-translate-php/tests/TranslationTest.php:16
6) Stichoza\GoogleTranslate\Tests\TranslationTest::testArrayTranslation
ErrorException: Client error: `POST http://translate.google.com/translate_a/t` resulted in a `403 Forbidden` response:
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, w (truncated...)
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:262
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:299
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:175
/home/limon/www/google-translate-php/tests/TranslationTest.php:26
7) Stichoza\GoogleTranslate\Tests\TranslationTest::testRawResponse
ErrorException: Client error: `POST http://translate.google.com/translate_a/t` resulted in a `403 Forbidden` response:
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, w (truncated...)
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:262
/home/limon/www/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:185
/home/limon/www/google-translate-php/tests/TranslationTest.php:44
Hi, so I discovered that the translation throws a Forbidden error when using unicode characters (I think that's what they are called). Here's an example:
I feel sad 😢
Translating these does not work. It seems that the d
array in TL
function contains too many items. So something inside this loop
for ($d = array(), $e = 0, $f = 0; $f < mb_strlen($a, 'UTF-8'); $f++) {
$g = $this->charCodeAt($a, $f);
if ( 128 > $g ) {
$d[$e++] = $g;
} else {
if ( 2048 > $g ) {
$d[$e++] = $g >> 6 | 192;
} else {
if ( 55296 == ($g & 64512) && $f + 1 < mb_strlen($a, 'UTF-8') && 56320 == ($this->charCodeAt($a, $f + 1) & 64512) ) {
$g = 65536 + (($g & 1023) << 10) + ($this->charCodeAt($a, ++$f) & 1023);
$d[$e++] = $g >> 18 | 240;
$d[$e++] = $g >> 12 & 63 | 128;
} else {
$d[$e++] = $g >> 12 | 224;
$d[$e++] = $g >> 6 & 63 | 128;
}
}
$d[$e++] = $g & 63 | 128;
}
}
does not work correctly with Unicode characters. My believe is that the function charCodeAt
is to blame. It does not return the same values as javascript's charCodeAt
for certain characters.
Maybe someone can help ..
`<?php
//Composer Loader
$dir = realpath(DIR.'/');
require $dir.'/vendor/autoload.php';
use Stichoza\GoogleTranslate\TranslateClient;
$tr = new TranslateClient('en', 'ka');
var_dump ($tr->translate(['I can dance', 'I like trains', 'Double rainbow']));`
//output
array (size=1)
0 => string '�' (length=1)
help to correct?
Hi, I'm getting this error later.
PHP Fatal error: Uncaught ErrorException: Client error:
POST http://translate.google.com/translate_a/single?client=t&hl=en&dt=t&sl=en&tl=es&ie=UTF-8&oe=UTF-8&multires=1&otf=0&pc=1&trs=1&ssel=0&tsel=0&kc=1&t k=387179.252693resulted in a
413 Request Entity Too Large response:
I think it's because the text to translate is too long.
But the big problem is that this error me for the execution of my script, I look for the way that if I receive some fatal error instead of stop the execution of the script to skip to the next and thus would not stop the execution of the script.
Any help I greatly appreciate.
I am working with the version 2.0.3 and following is my code its showing blank page
translate("Hello World!"); ?>Server error: POST http://translate.google.com/translate_a/t
resulted in a 503 Service Unavailable
response:
Nice class that mostly works but seems to have a small problem in certain cases.
For example I'm pulling in a YouTube video description in Russian:
Ставьте лайк и подписывайтесь если понравилось! Спасибо за просмотр :D\nLeave a like if you enjoyed and subscribe! Thanks for watching :D\n\nс вами Daev\n\n\nТеги***************************************************************************************************************************************************\n#Daev #world of tanks 9.6 #world of tanks арта #world of tanks артиллерия #world of tanks бонус код #world of tanks вбр #олени в world of tanks #как поднять кпд в world of tanks #как поднять стату в world of tanks #как поднять фпс в world of tanks #как играть в world of tanks #как заработать золото в world of tanks #world of tanks для новичков #world of tanks канал #world of tanks карты #world of tanks на русском #world of tanks обучение #world of tanks приколы и баги #world of tanks 60fps
and when I call $translate = GoogleTranslate::staticTranslate( $desc, "auto", "en" );
it returns FALSE
.
Debugging the staticTranslate function I can see the result returned by Google is Error 400 (Bad Request). It only happens sometimes so I'm wondering if rawurlencode
is tripping up on some of the text(?)
Does it have a problem with guzzle 6?
apparently it does?
Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.'
I am currently using 'auto' to automatically detect the original language, and it is working fine, what I am wondering is if is it possible to retrieve the detected language code ?
$tr = new TranslateClient; //($fromLanguage, $toLanguage);
$tr->setSource('de');
$tr->setTarget('en');
var_dump($tr->translate(['fahrrad', 'schule', 'baum']));
returns a one element array with just the letter f
:
array (size=1)
0 => string 'f' (length=1)
Any clue on why this can be happening?
Hi, I' am trying to send PHP_EOL (\n) symbols within my query, but I get the following error (403 Forbidden):
https://pastebin.com/pR9JEbKP
To do so I use in the input ($data) text blocks with three numbes like <666> and in TranslateClient.php in section private function getResponse($data)
I use the following replacement:
$data = str_replace('<888>', PHP_EOL, $data);
right before $queryArray = array_merge[..]
In the meantime, I' am able to decode the $queryBodyEncoded query with http://www.url-encode-decode.com/ and it shows that my query syntax (if it's a thing) is right (comparing to query without PHP_EOL).
So I assume that it's either Google don't like query with encoded PHP_EOL or I' am doing smth wrong.
Please help me.
Have this problem when run the composer, anyone know why?
Problem 1 - Can only install one of: stichoza/google-translate-php[v3.2.0, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.1, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.10, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.11, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.12, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.2, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.3, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.4, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.5, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.6, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.7, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.8, dev-master]. - Can only install one of: stichoza/google-translate-php[v3.2.9, dev-master]. - Installation request for stichoza/google-translate-php dev-master -> satisfiable by stichoza/google-translate-php[dev-master]. - Installation request for stichoza/google-translate-php ~3.2 -> satisfiable by stichoza/google-translate-php[v3.2.0, v3.2.1, v3.2.10, v3.2.11, v3.2.12, v3.2.2, v3.2.3, v3.2.4, v3.2.5, v3.2.6, v3.2.7, v3.2.8, v3.2.9].
Hi. I do not have composer. I do not plan on getting it. How would I use this with out composer, is it possible?
Few versions ago, I've built this webtool stringsxmlbuilder.netsons.org and all worked.
Now the translation made by this tool doesn't work, but if I transfer the website on localhost and I run it with xampp it works well.
What could be? How can I debug it?
Thanks
First of all thanks a lot, i really appreciate the work you did.
it helped me in my project.
i run the translation in my project and its working fine.
The only issue i am having is i want some words to be translated as according to user
not by google API.
so i want custom translation like i did with .PO and .MO files using gettext
Where we can put all the translation in one file .
please help me with this situation
I have:
use VCN\Repositories\AccountRepository as Account;
and try:
$res = $this->account->findAllBy('type',1);
and I receive this error:
[Symfony\Component\Debug\Exception\FatalErrorException]
Call to undefined method VCN\Repositories\AccountRepository::findAllB
y()
This is the remain of #32. Array translation is broken at this moment and should be fixed.
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.' in /Users/kmaxat/PhpstormProjects/untitled1/vendor/stichoza/google-translate-php/src/Stichoza/GoogleTranslate/Tokens/GoogleTokenGenerator.php:79
The makeCurl() function fails to clean up the temporary cookie jar files it creates in some environments.
This can cause errors in the /tmp folder where 65535 files block other services from using the folder, such as MySQL, leading to an Error 28.
I've made a pull request with a proposed fix.
How do i force Guzzle to use a http proxy via CURL ?
I have tried setting random non-existent proxies and the request always goes through , which means requests are not getting proxied , else i would not be getting a response.
I have tried a few things so far
This one from the documentation
$tr = new TranslateClient(null, 'es', [
'defaults' => [
'proxy' => [
'http' => 'http://username:[email protected]:xxxxx',
'https' => 'http://username:[email protected]:xxxxx'
],
]
]);
And this one from here - http://stackoverflow.com/q/28185987/3117013
$tr = new TranslateClient(null, 'es', [
'config' => [
'curl' => [
'CURLOPT_PROXY' => 'xx.xx.xx.xx',
'CURLOPT_PROXYPORT' => xxxxx,
'CURLOPT_PROXYUSERPWD' => 'username:password',
'CURLOPT_HTTPPROXYTUNNEL' => 1
]
]
]);
Any help is appreciated..
Seems like the the response for string translations has changed a little and does not require array merging anymore since the string is returned as a whole, can someone confirm this?
Warning: array_reduce() expects parameter 1 to be an array or collection in /../TranslateClient.php on line 333
I'm getting an error from guzzle
Fatal error: Class GuzzleHttp\Client contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (GuzzleHttp\Event\HasEmitterInterface::getEmitter) in /Applications/MAMP/htdocs/translate/vendor/guzzlehttp/guzzle/src/Client.php on line 403
That line is the very last line of the guzzle src file. My php is pretty straightforward I think
<?php
require 'vendor/autoload.php';
ini_set('display_errors', 'On');
use Stichoza\GoogleTranslate\TranslateClient;
$tr = new TranslateClient('en', 'ka');
echo $tr->translate('hello');
?>
Any ideas? Is this a environment specific thing I'm experiencing maybe?
Looking at my error log, I just found that if a special character (in my error log: 💘 - more info ) was entered in a sentence, something went wrong, and the folloing exception was raised:
'Client error: `POST http://translate.google.com/translate_a/single` resulted in a `403 Forbidden` response: <!DOCTYPE html> <html lang=en> <meta charset=utf-8> <meta name=viewport content="initial-scale=1, minimum-scale=1, w (truncated...) '
in /path/to/vendor/stichoza/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php:286
Stack trace:
#0 /path/to/vendor/stichoza/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php(323): Stichoza\GoogleTranslate\TranslateClient->getResponse('TEST \xF0\x9F\x92\x98')
#1 /path/to/vendor/stichoza/google-translate-php/src/Stichoza/GoogleTranslate/TranslateClient.php(185): Stichoza\GoogleTranslate\TranslateClient->instanceTranslate('TEST \xF0\x9F\x92\x98')
#2 /path/to/include/googletranslate.class.php(61): Stichoza\GoogleTranslate\TranslateClient->__call('translate', Array)
#3 /path/to/include/googletranslate.class.php(61): Stichoza\GoogleTranslate\TranslateClient->translate('TEST \xF0\x9F\x92\x98')
#4 /path/to/index.php(24): GoogleTranslate->getCode()
#5 {main} [] []
Of course Google Translate translates it, so for me, it looks like a bug in this project.
It can't translate if there is more than 1300 words.
Class not found issue coming when running test files
Library stopped working. Checking the response of the request to http://translate.google.com/translate_a/t it looks like a 503 Service Unavailable
Server error response [url] http://ipv4.google.com/sorry/IndexRedirect?continue=http%3A%2F%2Ftranslate.google.com%2Ftranslate_a%2Ft&q=CGMSBFcVvDgY76SYvgUiGQDxp4NLWjSyK9Kcfu_3QluMCB6pWX64XWE [status code] 503 [reason phrase] Service Unavailable
When I translate in a specific subject, the translator translates the words not as needed. For example, one word has several meanings, but only one word is translated. Support the filter of words to which my translation will be called.
Thanks for the translator script. I think the issue is more with Google than with your script. if html is translated, ends up as </ li> which isn't right. So one can't translate an article that has paragraphs and html elements without it breaking. So my question is more of a tip:
Can I possibly translate html without damaging the html codes? If yes, how? Any suggestion is appreciated.
Is it possible that the project needs an update?
Is it working for everyone else?
I think there is captcha problem when making frequent calls from given ip address
Hello,
You guys did a really great job but I have some issues when I translate english to french for exemple:
Chief Executives => directeurs Généraux.
Do you have any idea why?
Thank you
Best regards
SBerda
Unfortunately, I am not familiar with compose and the related technology. I tried to install according to both of your instructions
composer require stichoza/google-translate-php
https://github.com/Stichoza/google-translate-php/blob/master/composer.json
but none of them worked for me.
My application is written in CodeIgniter, third-party code should reside in the subdirectory plugins
.
This is the resulting directory layout of those 2 attempts:
The respective directory structure looks amazingly different:
The beginning of my PHP module looks like
As you see, I also experiment with DetectLanguage here which doesn't quite give me the results I need, which is why I finally stumbled over GoogleTranslate. It doesn't matter if I add a backslash at the beginning of the use instruction or not.
The function in case looks like
which results in the following error at $tr = new TranslateClient();,
no matter which of the 2 alternatives I choose.
I verified that the proper autoload
file is loaded in either case, so this is not the problem. The rest should be handled automatically, at least that's what I think the whole magic procedure is about.
What am I doing wrong? What is it that I don't understand? What do I have to do to make it work?
Thank you very much for any help. I tried to make it on my own, but I don't know how to phrase the problem correctly in order to find the solution.
Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING)
google-translate/src/Stichoza/GoogleTranslate/TranslateClient.php on line 92
PHP Version 5.4.45 Not Working And PHP Version 5.4
If i can collect paid api key then how can i use it ?
Hey!
it would be awesome to get a new release package so we dont have to pull from master.
thank you!
It doesn't work with me!
Hi!
I'm working on a project that uses this library, and I noticed that in the getResponse function, there is a try-catch block (line 288-295) around the Guzzle request, which just re-throws the error message. The problem is that, this way I can't really build a good error handling around the translation process, because I can't tell the difference between ConnectException, ClientException, ServerException, etc., which would be great in my opinion.
Do we really have to catch Guzzle RequestExceptions in getResponse?
Can you tell me, what is the purpose of catching and re-throwing the Exceptions there?
I have a very specific usecase where I need phonetic translations instead of dictionary ones. Is there a way, the api can be customized for the same?
Google translate does allow for phonetic translations as per article here: http://www.androidcentral.com/google-translate-app-gets-phonetic-support-more-languages
But I can translate them directly on google translate. Words like 'help', 'export' - getting nothing.
Just came across your package via a Laravel translation package which depends on it; the 3.2.1 release does not work at all for me due to the string response bug which appears to have been dealt with in master:
Can you please tag a new release so we can utilise this fix?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.