使用谷歌翻译API翻译PHP $字符串

时间:2011-01-09 16:52:20

标签: php google-translate

google'了一段时间用PHP翻译谷歌翻译的最好方法是什么,发现转换URLs或使用Js的方式非常不同但我想只用php(或者用一个非常简单的解决方案JS)来做/ JQUERY)

示例:

//hopefully with $from_lan and $to_lan being like 'en','de', .. or similar
function translate($from_lan, $to_lan, $text){

// do

return $translated_text;

}
你可以给我一个线索吗?或者你已经有了这个功能..

我的意图是将它仅用于我尚未定义的语言(或者我没有定义的键),这就是为什么我这么简单,只是暂时的...

修改

感谢您的回复我们现在正在尝试这个问题:

function auto_translate($from_lan, $to_lan, $text){
// do


$json = json_decode(file_get_contents('https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' . urlencode($text) . '&langpair=' . $from_lan . '|' . $to_lan));
$translated_text = $json->responseData->translatedText;


return $translated_text;

}

(无论如何,lang的变量还有一个额外的'g')

它返回:现在有效:)

我对这个功能并不是很了解,所以任何想法为什么都没有说出这个对象呢? (现在我这样做)

或者:

    function auto_translate($from_lan, $to_lan, $text){
    // do

//    $json = json_decode(file_get_contents('https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' . urlencode($text) . '&langpair=' . $from_lan . '|' . $to_lan));
//    $translated_text = $json['responseData']['translatedText'];
    error_reporting(1);
    require_once('GTranslate.php');
    try{
       $gt = new Gtranslate();
       $translated_text = $gt->english_to_german($text);

     } catch (GTranslateException $ge)
     {
           $translated_text= $ge->getMessage();
     }


    return $translated_text;
}

这个看起来很棒,但它甚至没有给我一个错误,页面也不会加载(error_report(1):S)

提前感谢!

5 个答案:

答案 0 :(得分:11)

我还没有测试过,但请尝试:

function translate($from_lan, $to_lan, $text){
    $json = json_decode(file_get_contents('https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=' . urlencode($text) . '&langpair=' . $from_lan . '|' . $to_lan));
    $translated_text = $json->responseData->translatedText;

    return $translated_text;
}

编辑:修复,测试和工作。

答案 1 :(得分:1)

我对此有新的解决方案。.因为最后一个解决方案需要新版本,并且获取了其他一些问题。


    $text = 'Test new message only.';
    $apiKey = '<past your google api key here>';
    $url = 'https://www.googleapis.com/language/translate/v2?key=' . $apiKey . '&q=' . rawurlencode($text) . '&source=en&target=fr';
    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($handle);
    $responseDecoded = json_decode($response, true);

    curl_close($handle);

    print_r($responseDecoded['data']['translations'][0]['translatedText']);
    die;

    //expected output
     Testez le nouveau message uniquement.

我希望对PHP很有帮助

答案 2 :(得分:0)

要在PHP中使用Google Translate API,您需要在创建以下类的对象后在composer文件中插入“ google / cloud-translate”和“ google / apiclient”,运行composer update并调用translation方法:

<?php

require_once APP_ROOT . '/library/google-api-php-client/src/Google_Client.php';
require_once APP_ROOT . '/library/google-api-php-client/src/contrib/Google_TranslateService.php';

class GoogleTranslator
{
    private $developer_key;

    const PROVIDER = "google";
    const SUCCESS = "success";
    const FAILURE = "failure";
    const TRANSLATE_SUCCESS_MESSAGE = 'text translation successful';

    public function __construct()
    {
        $this->developer_key = '<DEVELOPER KEY HERE>';
    }

    public function translate($text, $source_language, $target_language)
    {
        try {
            $client = new \Google_Client();
            $client->setApplicationName('Google Translate PHP Starter Application');

            $client->setDeveloperKey($this->developer_key);
            $service = new \Google_TranslateService($client);

            $optional_parameters = array('source' => $source_language);

            $translated_text = $service->translations->listTranslations($text, $target_language, $optional_parameters);
            return array('translation' => $translated_text['translations'][0]['translatedText'],
                'provider' => self::PROVIDER,
                'status' => self::SUCCESS,
                'message' => self::TRANSLATE_SUCCESS_MESSAGE);
        } catch (\Exception $e) {
            error_log($e->getMessage() . " FOR GET TRANSLATION CALL", "GOOGLE TRANSLATE API");
            $res = array('translation' => '',
                'provider' => self::PROVIDER,
                'status' => self::FAILURE,
                'message' => $e->getMessage());
            return $res;
        }
    }
}

答案 3 :(得分:0)

要获取有效的示例,请查看安装随附的README.md文件。 (在运行composer require google/cloud-translate之后)。

此页面在搜索中排名第一,因此有必要提供更新。甚至Google's own translating text (basic) PHP examples都不适合我。

截至2020年,这通过网络browser query strings返回了快速的结果。 如果要将sanitizing user input部署为某些前端应用程序或网站的一部分,请考虑使用。{p>

<?php
require 'vendor/autoload.php';
use Google\Cloud\Translate\V2\TranslateClient;

$txt  = $_GET["q"];
$src  = $_GET["s"];
$targ = $_GET["t"];

$translate = new TranslateClient([
    'key' => 'Your API Key Here'
]);

// Translate text from english to french.
$result = $translate->translate($txt, [
    'source' => $src,
    'target' => $targ,
]);

echo $result['text'];

答案 4 :(得分:0)

    <!DOCTYPE html>
<html lang="en-US">
<body>

<h1>My Web Page</h1>

<p>Hello everybody!</p>

<p>Translate this page:</p>


<div id="google_translate_element"></div>

<script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script>

<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

<p>You can translate the content of this page by selecting a language in the select box.</p>

</body>
</html>


<?php 


 ?>