PHP code example of rkwebsolution / translation-services
1. Go to this page and download the library: Download rkwebsolution/translation-services library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
rkwebsolution / translation-services example snippets
use Fastnet\TranslationServices\Facades\Translator;
// Translate text
$result = Translator::translate('Hello World', 'ar');
if ($result['success']) {
echo $result['translated_text']; // مرحبا بالعالم
}
// Use Google Translate
$result = Translator::useService('google')
->translate('Hello World', 'es');
// Use DeepL
$result = Translator::useService('deepl')
->translate('Hello World', 'de');
// Use OpenAI
$result = Translator::useService('openai')
->translate('Hello World', 'fr');
// Use Ollama locally
$result = Translator::useService('ollama')
->translate('Hello World', 'ur');
use Spatie\Translatable\HasTranslations;
class Product extends Model
{
use HasTranslations;
public array $translatable = ['name', 'description'];
}
// Translate model fields
$product = Product::find(1);
$results = Translator::translateModel(
model: $product,
fields: ['name', 'description'],
targetLanguage: 'ar',
sourceLanguage: 'en',
save: true
);
// Check results
foreach ($results as $field => $result) {
if ($result['success']) {
echo "{$field}: {$result['translated_text']}\n";
}
}
// Translate to multiple languages
$product = Product::find(1);
$languages = ['ar', 'es', 'fr', 'de'];
foreach ($languages as $lang) {
Translator::translateModel(
$product,
['name', 'description'],
$lang,
'en'
);
}
// Now you can use:
$product->getTranslation('name', 'ar');
$product->getTranslation('description', 'es');
use Fastnet\TranslationServices\TranslationManager;
$translator = new TranslationManager();
$result = $translator->translate('Hello World', 'ar');
use Fastnet\TranslationServices\TranslationManager;
class TranslationService
{
public function __construct(
private TranslationManager $translator
) {}
public function translateProduct(Product $product, string $language)
{
return $this->translator->translateModel(
$product,
['name', 'description'],
$language
);
}
}
// Test service configuration
$service = Translator::driver('google');
if ($service->isConfigured()) {
echo "Service is configured correctly\n";
}
// Test translation
$result = Translator::translate('Test', 'ar');
dd($result);