PHP code example of moyefu / translator

1. Go to this page and download the library: Download moyefu/translator 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/ */

    

moyefu / translator example snippets




use Moyefu\TranslatorFactory;

// Create Baidu translator
$baiduTranslator = TranslatorFactory::create('baidu', [
    'appId' => 'your_baidu_app_id',
    'key' => 'your_baidu_key'
]);

// Translate text
try {
    $result = $baiduTranslator->translate('Hello world', 'en', 'zh');
    echo 'Translation result: ' . $result;
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

// Create Google translator
$googleTranslator = TranslatorFactory::create('google', [
    'key' => 'your_google_key'
]);

// Create Youdao translator
$youdaoTranslator = TranslatorFactory::create('youdao', [
    'appId' => 'your_youdao_app_id',
    'key' => 'your_youdao_key'
]);

// Create Tencent translator
$tencentTranslator = TranslatorFactory::create('tencent', [
    'secretId' => 'your_tencent_secret_id',
    'secretKey' => 'your_tencent_secret_key'
]);

// Create Ali translator
$aliTranslator = TranslatorFactory::create('ali', [
    'accessKeyId' => 'your_ali_access_key_id',
    'accessKeySecret' => 'your_ali_access_key_secret'
]);

// Create Volcengine translator
$volcengineTranslator = TranslatorFactory::create('volcengine', [
    'accessKeyId' => 'your_volcengine_access_key_id',
    'accessKeySecret' => 'your_volcengine_access_key_secret'
]);

// Create Microsoft translator
$microsoftTranslator = TranslatorFactory::create('microsoft', [
    'apiKey' => 'your_microsoft_api_key',
    'endpoint' => 'your_microsoft_endpoint'
]);

// Set additional options
$translator->setOptions([
    'timeout' => 10, // 10 seconds timeout
    'verify' => true // Verify SSL certificates
]);

// Change API key dynamically
$translator->setKey('new_api_key');

// Translate multiple sentences
$texts = [
    'Hello world',
    'How are you?',
    'I am fine, thank you.'
];

foreach ($texts as $text) {
    try {
        $result = $translator->translate($text, 'en', 'zh');
        echo "Original: $text\n";
        echo "Translation: $result\n\n";
    } catch (Exception $e) {
        echo "Error translating '$text': " . $e->getMessage() . "\n";
    }
}
bash
vendor/bin/phpunit tests/TranslatorTest.php