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');

$texts = [
    'Hello World',
    'Good Morning',
    'Thank You'
];

$results = Translator::translateBatch($texts, 'ar');

foreach ($results as $result) {
    if ($result['success']) {
        echo $result['translated_text'] . "\n";
    }
}

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
        );
    }
}

[
    'success' => true,
    'translated_text' => 'مرحبا بالعالم',
    'source_language' => 'en',
    'target_language' => 'ar',
    'service' => 'google',
    'metadata' => [
        'model' => 'nmt',
        'confidence' => 0.99
    ],
    'error' => null
]

[
    'success' => false,
    'translated_text' => null,
    'source_language' => 'en',
    'target_language' => 'ar',
    'service' => 'google',
    'metadata' => [],
    'error' => [
        'message' => 'API key invalid',
        'code' => 401
    ]
]

$services = Translator::getAvailableServices();

foreach ($services as $service) {
    echo "{$service['display_name']}: " .
         ($service['configured'] ? 'Ready' : 'Not configured') . "\n";
}

if (Translator::hasService('deepl')) {
    $result = Translator::useService('deepl')
        ->translate('Hello', 'de');
}

use App\Models\Product;
use Fastnet\TranslationServices\Facades\Translator;

class ProductTranslationService
{
    public function translateAllProducts(string $targetLanguage)
    {
        $products = Product::all();
        $results = [];

        foreach ($products as $product) {
            try {
                $result = Translator::useService('deepl')
                    ->translateModel(
                        $product,
                        ['name', 'description', 'features'],
                        $targetLanguage,
                        'en',
                        true
                    );

                $results[] = [
                    'product_id' => $product->id,
                    'success' => !empty(array_filter($result, fn($r) => $r['success'])),
                    'details' => $result
                ];
            } catch (\Exception $e) {
                $results[] = [
                    'product_id' => $product->id,
                    'success' => false,
                    'error' => $e->getMessage()
                ];
            }
        }

        return $results;
    }
}

use Illuminate\Console\Command;
use Fastnet\TranslationServices\Facades\Translator;

class TranslateProductsCommand extends Command
{
    protected $signature = 'products:translate {language}';
    protected $description = 'Translate all products to specified language';

    public function handle()
    {
        $language = $this->argument('language');
        $products = Product::all();

        $this->withProgressBar($products, function ($product) use ($language) {
            Translator::translateModel(
                $product,
                ['name', 'description'],
                $language,
                'en'
            );
        });

        $this->info("\nTranslation completed!");
    }
}

$result = Translator::translate('Hello', 'ar');

if (!$result['success']) {
    Log::error('Translation failed', [
        'service' => $result['service'],
        'error' => $result['error']['message']
    ]);

    // Use fallback text
    $translatedText = $originalText;
} else {
    $translatedText = $result['translated_text'];
}

// 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);
bash
php artisan vendor:publish --tag=translation-services-config