PHPにて「みんなの自動翻訳」のAPIで指定したテキストの言語判定する方法
2024/10/03
迷惑メール対策等でメール本文が日本語のもののみ受信したい場合がある。ただ、本文内にURLやメールアドレスが入ることもあると思われるので正規表現でどうこうするというのは難しそう。そこで「みんなの自動翻訳」の言語判定APIを使えばいいんじゃないかと思った。以下に利用方法をメモ。
事前準備
「みんなの自動翻訳」についてと、事前準備については過去記事を参照すること。
利用方法
ソースコード
定数部分は適宜書き換えること。
<?php define('API_KEY', 'xxxxxxxxxxxx'); define('API_SECRET', 'xxxxxxxxxxxx'); define('API_NAME', 'xxxxxxxxxxxx'); //アクセストークンの取得 $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/langdetect/'; $text = "Quickly translate text and document files, whether you're working as an individual or as a team.テキストや文書ファイルを瞬時に翻訳します。個人でもチームでも、高精度の翻訳をご活用いただけます。"; $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']);
出力結果
以下のように「言語は日本語で類似度が91%」という結果が出力された。
array(1) { ["langdetect"]=> array(1) { [0]=> array(2) { ["lang"]=> string(2) "ja" ["rate"]=> float(0.91) } } }
所感
言語が日本語且つ類似度が〇%以上ならメール送信する、みたいな処理を入れることで迷惑メール対策になりそう。
関連記事
-
-
jQuery.uploadでリアルタイムプレビュー
やりたい事は、 ・<input type="file">で画像を選択 ...
-
-
PHPで定義済みの変数 / 定数とincludeしているファイル一覧を取得する方法
他社が作成されたPHPのファイルを読み解く際に、定義済みの変数 / 定数や、in ...
-
-
PHPのsetcookieで「Cannot modify」エラーの対応方法
PHPでsetcookieを使うと「Warning: Cannot modify ...
-
-
ブログサービスの様にサブドメインを動的に生成する方法
ブログサービスの様に「hoge」というログインIDを作成した際「hoge.blo ...
-
-
PHPで日付の比較
以前に「締切日を設けて、今日の日付と比較して分岐させる」というもので 日付の比較 ...