How To Translate CodeIgniter 3/4 language files with AI

2024-10-06 | 218 words

You want to translate your CodeIgniter project into multiple languages? Well, I have created a PHP library called codeigniter-ai-translation, which uses Anthropic’s Claude AI to translate your language files. You can install it via composer using the link above.

It supports CodeIgniter 3 and 4 and can deal with multidimensional arrays. You can modify the default prompt and also set a sleep time between requests to avoid rate limiting.

You can find source code on GitHub.

You will need to have an API key from Anthropic to use this library.

Example usage:

<?php
require_once __DIR__ . '/vendor/autoload.php';

$translator = new MichalSkoula\CodeIgniterAITranslation\Translator(
    'your-api-key',           // Anthropic Claude API key
    'cs',                     // source language (need to match you directory name)
    'en',                     // target language (need to match you directory name; will be created automatically)
    'application/language',   // path to your language files
    3                         // CodeIgniter version (3 - default, 4)
);

$translator->setPrompt('Translate the following text from language %s to language %s: %s');

// if $file is null, if will translate all files in the directory
$result = $translator->translate($file);

echo "Translation process completed." . PHP_EOL;
echo "Total files processed: " . $result->getProcessed() . PHP_EOL;
echo "Total items translated: " . $result->getTranslated() . PHP_EOL;
echo "Total items failed: " . $result->getFailed() . PHP_EOL;
if ($result->isError()) {
    echo 'Error: ' . $result->getErrorMessage() . PHP_EOL;
}