PHP - Traduzindo Textos via API do Google Translation
Aprenda a traduzir textos automaticamente usando a API do Google Translation. Crie uma API Key no Google Cloud Platform, ative a Cloud Translation API e envie requisições POST para traduzir textos de forma eficiente.

Olá meus Unicórnios! 🦄✨
Traduzir grandes quantidades de texto manualmente é loucura, um tempo gigante sendo perdido.
Uma solução barata é utilizar a API do Google Translation, para isto, primeiramente, precisamos criar uma API KEY.
Gerando nossa API KEY
Acesso o Console de APIs do Google:

Crie ou selecione um dos projetos:

Clique em "Credenciais" e clique em "Criar Credenciais -> Chave de API":

Copie a API KEY:

Agora precisamos ativar o Google Translation neste Projeto, para isto, clique em "APIs e Serviços Ativados" e em seguida em "ATIVAR APIS E SERVIÇOS":

Procure por "Cloud Translation API":

Clique em "Cloud Translation API":

Clique em "Ativar":

Pronto! Agora já podemos utilizar a API.
Fazendo uma Tradução
Para este teste, iremos traduzir o texto "Oi" do Português para o Inglês.
As traduções são feitas, enviando um POST para:
https://translation.googleapis.com/language/translate/v2
Com os parâmetros a seguir:
- q: O texto Origem
- source: O idioma de Origem, neste exemplo, "pt-BR"
- target: O idioma de Destino, neste exemplo, "en"
- key: A API Key que geramos no Console da Google
O retorno, será uma HttpCode 200, onde a tradução fica em "data.translations[0].translatedText":
{
"data": {
"translations": [
{
"translatedText": "Hey"
}
]
}
}
No final, iremos ter uma requisição semelhante a requisição abaixo:
<?
// ----------------------
$Params = array();
$Params["key"] = "XXXXXXXXXXXXXXXXX";
$Params["q"] = "oi";
$Params["source"] = "pt-BR";
$Params["target"] = "en";
$ParamsTxt = http_build_query($Params);
// ----------------------
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://translation.googleapis.com/language/translate/v2");
curl_setopt($ch, CURLOPT_POSTFIELDS, $ParamsTxt);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FILETIME, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$GetUrl = curl_exec($ch);
$GetUrl2 = json_decode($GetUrl, true);
curl_close($ch);
// ----------------------
echo $GetUrl2["data"]["translations"][0]["translatedText"];
// ----------------------
?>
Por hoje é só, meus unicórnios! 🦄✨
Que a magia do arco-íris continue brilhando em suas vidas! Até mais! 🌈🌟