php - 如何在不被阻止的情况下将免费的谷歌翻译 api 与 codeigniter 集成?
问题描述
我正在尝试将 Google translate Api 与 codeigniter 集成,起初它可以工作,但经过几次请求后我收到此错误302 Moved
,似乎服务器阻止了我的 IP 地址。
<?php
class GoogleTranslate
{
public static function translate($source, $target, $text)
{
$response = self::requestTranslation($source, $target, $text);
$translation = self::getSentencesFromJSON($response);
return $translation;
}
protected static function requestTranslation($source, $target, $text)
{
$url = "https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=es-ES&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e";
$fields = array(
'sl' => urlencode($source),
'tl' => urlencode($target),
'q' => urlencode($text)
);
$fields_string = "";
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
protected static function getSentencesFromJSON($json)
{
$sentencesArray = json_decode($json, true);
$sentences = "";
foreach ($sentencesArray["sentences"] as $s) {
$sentences .= isset($s["trans"]) ? $s["trans"] : '';
}
return $sentences;
}
}
$trans = new GoogleTranslate();
$result = $trans->translate($source, $target, $text);
我使用一个包含许多应该翻译的文本的数组。如何使用谷歌翻译 API 而不被阻止?
解决方案
使用官方谷歌翻译 API,见https://cloud.google.com/translate/docs/
Google 每个月都会免费为您提供 10 美元的信用额度。这意味着每月免费翻译 500 000 个字符。
推荐阅读
- java - 使用 Collections.binarySearch() 进行谓词搜索(即不完全匹配)
- javascript - 如何从用 xml 字符包装的 json 访问数据?
- ruby - RubyMine 可以检测 _spec.rb 文件并在单击运行/调试时显示它们吗?
- objective-c - 从 NSPasteboard mac 获取剪贴板的对象
- rust - 如何生成随机 num::BigUint?
- firebase - Firebase 云功能节点折旧警告
- c# - 数组的反向排序
- dart - Flutter - 用于绘图书页面的 TextPainter 与段落
- css - ReactJS - 导入组件会破坏 webpack
- android - java.lang.NullPointerException:com.bumptech.glide.util 中的参数不能为空