Method: Real-Time Translation Using Google Translate API
Author : Kundan kumar | Date : 20-02-2025
Get Google Translate API Key
Sign up at Google Cloud Console
Enable the Google Cloud Translation API
Get an API key from Credentials โ API Key
<?php ?>
Create a Translation Helper in CodeIgniter 4
Create a helper file:
๐ app/Helpers/translation_helper.php
function translate($text, $targetLang = 'en')
{
$apiKey = 'YOUR_GOOGLE_TRANSLATE_API_KEY';
$url = "https://translation.googleapis.com/language/translate/v2?key={$apiKey}&q=" . urlencode($text) . "&target={$targetLang}";
$response = file_get_contents($url);
$json = json_decode($response, true);
return $json['data']['translations'][0]['translatedText'] ?? $text;
}
Autoload the Helper
In app/Config/Autoload.php, add 'translation' to helpers:
public $helpers = ['url', 'form', 'translation'];
Modify Your Controller to Use Auto-Translation
๐ app/Controllers/MockTestController.php
namespace App\Controllers;
use App\Models\MockTestModel;
use CodeIgniter\Controller;
class MockTestController extends Controller
{
public function show($id)
{
$model = new MockTestModel();
$mockTest = $model->find($id);
$lang = session()->get('lang') ?? 'hi'; // Default language is Hindi
$data['title'] = ($lang === 'hi') ? $mockTest->title : translate($mockTest->title, $lang);
$data['description'] = ($lang === 'hi') ? $mockTest->description : translate($mockTest->description, $lang);
return view('mock_test_view', $data);
}
public function switchLanguage($lang)
{
session()->set('lang', $lang);
return redirect()->back();
}
}
Modify View to Display Translated Content
๐ app/Views/mock_test_view.php
<h1><?= esc($title); ?></h1>
<p><?= esc($description); ?></p>
<!-- Language Switch Links -->
<a href="<?= site_url('switch-language/en'); ?>">English</a> |
<a href="<?= site_url('switch-language/hi'); ?>">เคนเคฟเคจเฅเคฆเฅ</a>
Define Routes
๐ app/Config/Routes.php
$routes->get('switch-language/(:segment)', 'MockTestController::switchLanguage/$1');
Final Output
Now when you click "English", it will:
1๏ธโฃ Store 'en' in the session
2๏ธโฃ Automatically translate all content using Google Translate API
3๏ธโฃ Show the translated content without modifying your database
Advantages of This Approach
โ
No need to store translations manually
โ
Works for all dynamic content: blogs, mock tests, current affairs, etc.
โ
Supports multiple languages
โ
Easy to implement, no database changes
๐ Let me know if you want help setting up the API key! ๐
Comments:
No comments yet. Be the first to comment!