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)
}
}
}
所感
言語が日本語且つ類似度が〇%以上ならメール送信する、みたいな処理を入れることで迷惑メール対策になりそう。
関連記事
-
-
フォルダにリンク制限をかける
imgというフォルダがあり、直接URLを叩いても 中身を見られないけど、同一サー ...
-
-
PHPで携帯(スマホ含)とPCの判別
PHPにて携帯(スマホ含む)とPCで処理を振り分けたかったのでメモ。 <? ...
-
-
GoogleアナリティクスのデータをPHPで取得する方法
Googleアナリティクスの特定データをPHPで取得して、当該データを表示なりC ...
-
-
PHPにて短縮URLを展開させて、元のURLを取得する方法
短縮されたURLを展開させて、元のURLを取得したいというケースがあった。方法を ...
-
-
PHPでサイトURLからtitleとRSS用URLを取得
サイトのURLからRSS用URLとサイトタイトルを自動で取得したかった。その方法 ...