简体   繁体   中英

Google translate api cUrl not working in a Laravel 5 project

I am getting a server response of 0 each time I try and fetch the response using standard cUrl functionality within a Laravel project. It has nothing to do with this combination I think as when I access a way other URL it works fine... So I am now kinda lost...

In my controller I have a function like below:

$curl = "https://www.googleapis.com/language/translate/v2?key=MY-KEY&source=EN&target=NL&q=Hello%20world";
echo $curl;
$handle = curl_init($curl);
curl_setopt($handle, CURLOPT_URL, $curl);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($handle);
$responseDecoded = json_decode($response, true);

$responseCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($responseCode != 200) {
    echo 'Fetching translation failed! Server response code:' . $responseCode;
}
else {
    echo 'Source: ' . $text . '<br>';
    echo $responseDecoded['data'];
}
curl_close($handle);

The output is zero and the error code is 0 (zero)

While when I access the https://www.googleapis.com/language/translate/v2?key=MY-KEY&source=EN&target=NL&q=Hello%20world URL I get a perfect response "Hallo wereld"

Using for example $curl = http://www.jsontest.com/ the output is correct.

Can someone see what I am doing wrong here?

Stichoza/google-translate-php is a nice alternative for what you're trying to perform:

use Stichoza\GoogleTranslate\TranslateClient;

$tr = new TranslateClient('en', 'nl');
dd($tr->getResponse('Hello World'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM