LoginSignup
7
6

More than 5 years have passed since last update.

【PHP】API Keyなしで使えるGoogle翻訳ライブラリを見つけたので使ってみる

Posted at

API Keyの登録をしないで使えるGoogle翻訳のPHPライブラリないかなーと探していたら、見つけたので使ってみます。

GitHub:https://github.com/ammarfaizi2/GoogleTranslate
Packagist:https://packagist.org/packages/ammarfaizi2/googletranslate

使ってみる

インストール

>composer require ammarfaizi2/googletranslate
Using version ^0.0.1 for ammarfaizi2/googletranslate
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing ammarfaizi2/googletranslate (0.0.1): Downloading (100%)
Writing lock file
Generating autoload files

テストコード

拙作の「【随時更新】一風変わったWeb APIをまとめてみた」で紹介しているチャックノリスAPIを呼び出して、戻ってきたジョークを翻訳してみます。

ChuckNorrisFact.php
<?php
require "vendor/autoload.php";

use GoogleTranslate\GoogleTranslate;

// チャックノリスAPIの呼び出し
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.chucknorris.io/jokes/random');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
$chuckNorrisFact = json_decode($response, true);

// 結果を翻訳
$text = $chuckNorrisFact['value'];
$from = "en"; // English
$to   = "ja"; // 日本語
$st = new GoogleTranslate($text, $from, $to);
$result = $st->exec();
?>

<html>
    <body>
    <h2>翻訳前</h2>
    <p><?= $text ?></p>
    <h2>翻訳後</h2>
    <p><?= $result ?></p>
    </body>
</html>

image.png

余計なローマ字読みがくっついてきてますがちゃんと翻訳できてます!

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6