勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

PHPにて「みんなの自動翻訳」のAPIで日本語から英語に翻訳する方法

  PHP

翻訳用の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

  関連記事

PHP8系で「Uncaught TypeError: Unsupported operand types」エラー対応方法

PHP8系で「Fatal error: Uncaught TypeError: ...

Smartyでテンプレートファイル(tplファイル)を編集しても反映されない

Smartyで作成されたシステムがあり、一部修正でtplファイルを編集したものの ...

PHPで配列に特定の値が入っているか検索

PHPで配列に特定の値が入っているか検索して trueかfalseを返したい、と ...

PHPで配列じゃないものに対してソート

PHP Warning:  sort() expects parameter 1 ...

PHPのheader関数で気になった点

結論としてページの移転の場合はexitか ページ自体を消した方がよさ下。 &nb ...