Code Monkey home page Code Monkey logo

google-translate-php's Introduction

Google Translate PHP

Latest Stable Version Total Downloads Downloads Month Petreon donation PayPal donation

Free Google Translate API PHP Package. Translates totally free of charge.


Installation

Install this package via Composer.

composer require stichoza/google-translate-php

Note PHP 8.0 or later is required. Use following versions of this package for older PHP versions:

Package version PHP Version Documentation
^5.1 PHP >= 8.0 v5 Docs
^4.1 PHP >= 7.1 v4 Docs
^3.2 PHP < 7.1 v3 Docs

Basic Usage

Create GoogleTranslate object

use Stichoza\GoogleTranslate\GoogleTranslate;

$tr = new GoogleTranslate('en'); // Translates into English

Or you can change languages later

$tr = new GoogleTranslate(); // Translates to 'en' from auto-detected language by default
$tr->setSource('en'); // Translate from English
$tr->setSource(); // Detect language automatically
$tr->setTarget('ka'); // Translate to Georgian

Translate sentences

echo $tr->translate('Hello World!');

Also, you can also use method chaining

echo $tr->setSource('en')->setTarget('ka')->translate('Goodbye');

Or call a shorthand static method trans

echo GoogleTranslate::trans('Hello again', 'ka', 'en');

Advanced Usage

Language Detection

To detect language automatically, just set the source language to null:

$tr = new GoogleTranslate('es', null); // Or simply do not pass the second parameter 
$tr->setSource(); // Another way

Use getLastDetectedSource() to get detected language:

$tr = new GoogleTranslate('fr');

$text = $tr->translate('Hello World!');

echo $tr->getLastDetectedSource(); // Output: en

Return value will be null if the language couldn't be detected.

Supported Languages

You can get a list of all the supported languages using the languages method.

$tr = new GoogleTranslate();

$languages = $tr->languages(); // Get supported languages in iso-639 format

// Output: [ 'ab', 'ace', 'ach', 'aa', 'af', 'sq', 'alz', ... ]

Optionally, pass a target language code to retrieve supported languages with names displayed in that language.

$tr = new GoogleTranslate();

$languages = $tr->languages('en'); // Get supported languages, display name in english
// Output: [ 'en' => English', 'es' => 'Spanish', 'it' => 'Italian', ... ]

echo $languages['en']; // Output: 'English'
echo $languages['ka']; // Output: 'Georgian'

Same as with the translate/trans methods, you can also use a static langs method:

GoogleTranslate::langs();
// Output: [ 'ab', 'ace', 'ach', 'aa', 'af', 'sq', 'alz', ... ]

GoogleTranslate::langs('en');
// Output: [ 'en' => English', 'es' => 'Spanish', 'it' => 'Italian', ... ]

Supported languages are also listed in Google API docs.

Preserving Parameters

The preserveParameters() method allows you to preserve certain parameters in strings while performing translations. This is particularly useful when dealing with localization files or templating engines where specific placeholders need to be excluded from translation.

Default regex is /:(\w+)/ which covers parameters starting with :. Useful for translating language files of Laravel and other frameworks. You can also pass your custom regex to modify the parameter syntax.

$tr = new GoogleTranslate('de');

$text = $tr->translate('Page :current of :total'); // Seite :aktuell von :gesamt

$text = $tr->preserveParameters()
           ->translate('Page :current of :total'); // Seite :current von :total

Or use custom regex:

$text = $tr->preserveParameters('/\{\{([^}]+)\}\}/')
           ->translate('Page {{current}} of {{total}}'); // Seite {{current}} von {{total}}

You can use same feature with static trans() method too.

GoogleTranslate::trans('Welcome :name', 'fr', preserveParameters: true); // Default regex

GoogleTranslate::trans('Welcome {{name}}', 'fr', preserveParameters: '/\{\{([^}]+)\}\}/'); // Custom regex

Using Raw Response

For advanced usage, you might need the raw results that Google Translate provides. you can use getResponse method for that.

$responseArray = $tr->getResponse('Hello world!');

Custom URL

You can override the default Google Translate url by setUrl method. Useful for some countries

$tr->setUrl('http://translate.google.cn/translate_a/single'); 

HTTP Client Configuration

This package uses Guzzle for HTTP requests. You can pass an array of guzzle client configuration options as a third parameter to GoogleTranslate constructor, or just use setOptions method.

You can configure proxy, user-agent, default headers, connection timeout and so on using this options.

$tr = new GoogleTranslate('en', 'ka', [
    'timeout' => 10,
    'proxy' => [
        'http'  => 'tcp://localhost:8125',
        'https' => 'tcp://localhost:9124'
    ],
    'headers' => [
        'User-Agent' => 'Foo/5.0 Lorem Ipsum Browser'
    ]
]);
// Set proxy to tcp://localhost:8090
$tr->setOptions(['proxy' => 'tcp://localhost:8090'])->translate('Hello');

// Set proxy to socks5://localhost:1080
$tr->setOptions(['proxy' => 'socks5://localhost:1080'])->translate('World');

For more information, see Creating a Client section in Guzzle docs.

Custom Token Generator

You can override the token generator class by passing a generator object as a fourth parameter of constructor or just use setTokenProvider method.

Generator must implement Stichoza\GoogleTranslate\Tokens\TokenProviderInterface.

use Stichoza\GoogleTranslate\Tokens\TokenProviderInterface;

class MyTokenGenerator implements TokenProviderInterface
{
    public function generateToken(string $source, string $target, string $text): string
    {
        // Your code here
    }
}

And use:

$tr->setTokenProvider(new MyTokenGenerator);

Translation Client (Quality)

Google Translate has a parameter named client which defines quality of translation. First it was set to webapp but later google added gtx value which results in a better translation quality in terms of grammar and overall meaning of sentences.

You can use ->setClient() method to switch between clients. For example if you want to use older version of translation algorithm, type $tr->setClient('webapp')->translate('lorem ipsum...'). Default value is gtx.

Errors and Exception Handling

Static method trans() and non-static translate() and getResponse() methods will throw following exceptions:

  • ErrorException If the HTTP request fails for some reason.
  • UnexpectedValueException If data received from Google cannot be decoded.

As of v5.1.0 concrete exceptions are available in \Stichoza\GoogleTranslate\Exceptions namespace:

  • LargeTextException If the requested text is too large to translate.
  • RateLimitException If Google has blocked you for excessive amount requests.
  • TranslationRequestException If any other HTTP related error occurs during translation.
  • TranslationDecodingException If the response JSON cannot be decoded.

All concrete exceptions are backwards compatible, so if you were using older versions, you won't have to update your code.

TranslationDecodingException extends UnexpectedValueException, while LargeTextException, RateLimitException and TranslationRequestException extend ErrorException that was used in older versions (<5.1.0) of this package.

In addition, translate() and trans() methods will return null if there is no translation available.

Known Limitations

  • 503 Service Unavailable response: If you are getting this error, it is most likely that Google has banned your external IP address and/or requires you to solve a CAPTCHA. This is not a bug in this package. Google has become stricter, and it seems like they keep lowering the number of allowed requests per IP per a certain amount of time. Try sending less requests to stay under the radar, or change your IP frequently (for example using proxies). Please note that once an IP is banned, even if it's only temporary, the ban can last from a few minutes to more than 12-24 hours, as each case is different.
  • 429 Too Many Requests response: This error is basically the same as explained above.
  • 413 Request Entity Too Large response: This error means that your input string is too long. Google only allows a maximum of 5000 characters to be translated at once. If you want to translate a longer text, you can split it to shorter parts, and translate them one-by-one.
  • 403 Forbidden response: This is not an issue with this package. Google Translate itself has some problems when it comes to translating some characters and HTML entities. See #119 (comment)

Disclaimer

This package is developed for educational purposes only. Do not depend on this package as it may break anytime as it is based on crawling the Google Translate website. Consider buying Official Google Translate API for other types of usage.

Donation

If this package helped you reduce your time to develop something, or it solved any major problems you had, feel free to give me a cup of coffee :)

google-translate-php's People

Contributors

a-drew avatar abenomar-uma avatar baijunyao avatar chapeupreto avatar chitzi avatar consatan avatar deniszhitnyakov avatar fcorbi avatar gogromat avatar hadjedjvincent avatar iflamed avatar kreerc avatar kylemilloy avatar limonte avatar neoteknic avatar razzo1987 avatar rivajunior avatar rraallvv avatar scrutinizer-auto-fixer avatar stichoza avatar subsan avatar tanmuhittin avatar tehmaestro avatar timcotten avatar untoreh avatar vostreltsov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-translate-php's Issues

Error 403 Forbidden

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?

Filter for special words

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.

PHP Fatal error: Uncaught ErrorException: Client error: `POST http://translate.google.com/translate_a/

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 a413 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.

Your requirements could not be resolved to an installable set of packages.

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].

getResponse() error while trying to send query with PHP_EOL

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.

would it be possible to recognize language?

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 ?

response change

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

Installation woes

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:

st6

The respective directory structure looks amazingly different:

st7

st8

The beginning of my PHP module looks like

st4

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

st5

which results in the following error at $tr = new TranslateClient();, no matter which of the 2 alternatives I choose.

st3

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.

Its not working for me :(

I am working with the version 2.0.3 and following is my code its showing blank page

translate("Hello World!"); ?>

new release

Hey!

it would be awesome to get a new release package so we dont have to pull from master.
thank you!

Multi sentence translation doesn't seem to work

$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?

Issues with special characters (emojis 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.

POST http://translate.google.com/translate_a/t resulted in a `403 Forbidden` response

 ./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

guzzle dependency

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.'

Warning: open_basedir restriction in effect

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?

403 on strings with unicode characters

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 ..

How to set Guzzle to use HTTP proxy ?

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..

Do we really have to catch Guzzle RequestException in getResponse?

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?

Why now does it works only in localhost?

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

multiple sentence/array translation - error

`<?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?

[3.2] ErrorException in TranslateClient.php line 298

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;
        }
    }
}

Translating with HTML

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.

CAPTCHA

I think there is captcha problem when making frequent calls from given ip address

Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): It is not safe to rely on the system's timezone settings.

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

Can you please tag a new release

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:

22d078d

Can you please tag a new release so we can utilise this fix?

UTF8 Issues

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

Php 5.4 Version Not Working

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

Call to undefined method findAllBy()

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()

Support array of strings

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.

Custom translation

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

Google returning Error 400 (Bad Request) for certain queries.

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(?)

Error on get translate

Server error: POST http://translate.google.com/translate_a/t resulted in a 503 Service Unavailable response:

Guzzle http error

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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.