PHP code example of mantoufan / yzhantranslator

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

    

mantoufan / yzhantranslator example snippets


use YZhanTranslator\YZhanTranslator;

$translator = new YZhanTranslator([
    'client' => 'OpenAI',
    'apiKey' => 'your_openai_api_key',
    'apiUrl' => 'https://api.openai.com',
    'organization' => 'your_openai_organization_id',
]);

$result = $translator->translate('Hello, world!', 'zh-CN');
echo $result; // 你好,世界!

$json = json_encode(['greeting' => 'Hello']);
$result = $translator->translate($json, 'zh-CN', ['type' => 'json']);
print_r($result); // ['greeting' => '你好']

$languages = ['en', 'zh-CN', 'zh-TW', 'jp'];
$detectedLang = $translator->detect('こんにちは', $languages);
echo $detectedLang; // jp

$json = json_encode(['greeting' => 'こんにちは']);
$languages = ['en', 'zh-CN', 'zh-TW', 'jp'];
$detectedLang = $translator->detect($json, $languages);
echo $detectedLang; // jp

$json = json_encode(['k' => '你好']);
$prompt = 'If there is a key named \'k\', retain the original value, but add a new key \'k2\' at the same level, containing the translated value.';
$result = $translator->translate($json, 'en', [
    'type' => 'json',
    'prompt' => $prompt
]);
print_r($result); // ['k' => '你好', 'k2' => 'Hello']

use YZhanTranslator\YZhanTranslator;

$translator = new YZhanTranslator([
    'client' => 'OpenAI',
    'apiKey' => 'your_openai_api_key',
    'apiUrl' => 'https://api.openai.com',
    'organization' => 'your_openai_organization_id',
]);

$images = [
    'https://example.com/image1.jpg',
    'https://example.com/image2.jpg',
];
$result = $translator->translate(json_encode($images), 'zh-CN', ['type' => 'images']);
print_r($result); // ['https://example.com/image1.jpg' => ['description' => ''], 'https://example.com/image2.jpg' => ['description' => '']]

$result = $translator->translate('Hello, world!', 'zh-CN', [
    'prompt' => 'Translate in a formal tone',
    'cache' => [
        'type' => 'File',
        'params' => ['dir' => '/tmp/cache'],
        'maxAge' => 3600
    ],
    'timeout' => 10
]);