PHPにて「みんなの自動翻訳」のAPIで日本語から英語に翻訳する方法
翻訳用のWeb APIを利用しようとすると「月に〇〇リクエストまでは無料」とかだったりする。また、当然ながらクレジットカード登録も必要になる。そこで完全無料且つクレジットカード登録が不要のものが無いか探したところ「みんなの自動翻訳」というAPIが良さそう。以下にPHPにて日本語から英語に翻訳する方法をメモ。
みんなの自動翻訳
公式サイト
https://mt-auto-minhon-mlt.ucri.jgn-x.jp/
Web API一覧
https://mt-auto-minhon-mlt.ucri.jgn-x.jp/content/api/
事前準備
こちらのページからアカウントを作成し以下をメモっておく。
- ユーザーID
- API key
- API secret
API key / secretについてはログイン後、Web API一覧ページで「OAuth2.0 トークン取得」ボタンをクリックすると表示される筈。
利用方法
ソースコード
定数部分は適宜書き換えること。
<?php
define('API_KEY', 'xxxxxxxxxxxx'); //API key
define('API_SECRET', 'xxxxxxxxxxxx'); //API secret
define('API_NAME', 'xxxxxxxxxxxx'); //ユーザーID
//アクセストークンの取得
$token_url = 'https://mt-auto-minhon-mlt.ucri.jgn-x.jp/oauth2/token.php';
$data = [
'grant_type' => 'client_credentials',
'client_id' => API_KEY,
'client_secret' => API_SECRET
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$res = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if( !curl_errno($ch) && $http_code == '200' ){
$res = json_decode($res, true);
$access_token = $res['access_token'];
}else{
echo 'ERROR: ' . curl_error($ch);
exit();
}
curl_close($ch);
//翻訳
$translation_url = 'https://mt-auto-minhon-mlt.ucri.jgn-x.jp/api/mt/generalNT_ja_en/';
$text = 'テキストや文書ファイルを瞬時に翻訳します。個人でもチームでも、高精度の翻訳をご活用いただけます。';
$data = [
'text' => $text,
'key' => API_KEY,
'access_token' => $access_token,
'name' => API_NAME,
'type' => 'json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $translation_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$res = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if( !curl_errno($ch) && $http_code == '200' ){
$res = json_decode($res, true);
}else{
echo 'ERROR: ' . curl_error($ch);
exit();
}
curl_close($ch);
var_dump($res['resultset']['result']['text']); //string(96) "Quickly translate text and document files, whether you're working as an individual or as a team."
出力結果
コメントにも書いてあるが以下が出力された。
Quickly translate text and document files, whether you're working as an individual or as a team.
ちなみに上記結果をGoogleで逆翻訳すると以下内容になった。
個人で作業している場合でも、チームで作業している場合でも、テキスト ファイルやドキュメント ファイルをすばやく翻訳できます。
所感
無料で利用できクレジットカード登録不要なのが良い。翻訳以外にも良さそうなAPIがいくつか見受けられたので他のものも試してみたいところ。
関連記事
-
-
Composer自体のインストールとmonolog及びTwigをComposer経由でインストールする方法
「Composerで○○をインストール」というのをよく見かけるがComposer ...
-
-
PHPでテンプレートPDFに動的に文字や数値を追記し出力する方法(TCPDF&FPDI)
請求書や領収書のテンプレートがあり、そちらに対して動的に文字・数値を追記し出力さ ...
-
-
PHPで画像を比較して類似度を算出する「image-comparator」ライブラリの利用方法
PHPで画像の類似度を計測したい。ただ、そのためのロジックが全く分からないためラ ...
-
-
PHPのintval
intvalという見たこと無い関数があったのでメモ。 ■リファレンス http: ...
-
-
Codeigniter3で外部ファイル(CSS / JS)の読み込みと共通パーツ化する方法
CodeigniterでCSSやJSファイル等の外部ファイル読み込みたかった。ま ...