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がいくつか見受けられたので他のものも試してみたいところ。
関連記事
-
-
PHPでソーシャル(SNS)ログインする方法2018
久しぶりにソーシャル(SNS)ログインを実装する機会があった。以前に対応方法を書 ...
-
-
PHPでルーティング用ライブラリ「AltoRouter」の利用方法
PHPフレームワークのCodeIgniterを勉強していた際にルーティング機能が ...
-
-
Mailtrap & PHPMailerでメールサーバ無しの環境でもメール送信テストを行う方法
開発環境等メールサーバが無い環境でメール送信テストを行う際にMailtrapとい ...
-
-
PHPでtry~catch文
PHPでもあるってのを知らなかったのでメモ。 ■参考サイト http://www ...
-
-
PHPを用いてフォームからzipファイルをアップロードしサーバ上で解凍(展開)させる方法
formからzipファイルをアップロードしサーバ上で解凍(展開)するという一連の ...