使用Google Translator API翻译PHP $ string [英] translate a PHP $string using google translator API

查看:100
本文介绍了使用Google Translator API翻译PHP $ string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Google中待了一会儿,如何在PHP中使用Google Translator进行翻译的最佳方法是如何找到转换URL或使用Js的方法却非常不同,但我只想使用php(或使用非常简单的JS解决方案) /JQUery)

been google'ing for a while how is the best way to translate with google translator in PHP, found very different ways converting URLS, or using Js but i want to do it only with php (or with a very simple solution 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;

}

你能给我一个线索吗?也许您已经拥有此功能.

can you give me a clue? or maybe you already have this function..

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

my intention it's to use it only for the languages i have not already defined (or keys i haven't defined), that's why i wan it so simple, will be only temporal..

编辑

感谢您的答复,我们现在正在尝试以下说明:

thanks for your replies we are now trying this soulutions:

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

(there was a extra 'g' on variables for lang... anyway)

它返回:现在可以工作了:)

it returns: works now :)

我对功能并不太了解,所以知道为什么不接受该对象吗? (现在我知道了)

i don't really understand much the function, so any idea why is not acepting the object? (now i do)

OR:

    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)

And this one looks great but it doesn't even gives me an error, the page won't load (error_report(1) :S)

提前谢谢!

推荐答案

我尚未对此进行测试,但是请尝试:

I haven't tested this yet, but try:

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

已修复,经过测试且可以正常工作.

Fixed, tested and works.

这篇关于使用Google Translator API翻译PHP $ string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆