PHPackages                             mantoufan/yzhantranslator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. mantoufan/yzhantranslator

ActiveLibrary[Caching](/categories/caching)

mantoufan/yzhantranslator
=========================

Language translater using OpenAI with cache. 使用 AI 翻译内容到不同语言，缓存结果以节省费用.

2.1.2(1y ago)11331MITPHPPHP &gt;=5.4

Since Oct 3Pushed 1y ago1 watchersCompare

[ Source](https://github.com/mantoufan/yzhanTranslator)[ Packagist](https://packagist.org/packages/mantoufan/yzhantranslator)[ RSS](/packages/mantoufan-yzhantranslator/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (3)Versions (20)Used By (0)

YZhanTranslator
===============

[](#yzhantranslator)

YZhanTranslator is a PHP library for translating content using OpenAI's language models with caching capabilities. It supports translating strings, JSON objects and images arrays, as well as language detection.
YZhanTranslator can automatically cache (configurable) results to save costs.

Features
--------

[](#features)

- Translate strings and JSON objects
- Detect language of input text (including JSON content)
- Translate images by providing URLs and receiving descriptions
- Cache translation results to save costs
- Customizable prompts for fine-tuned translations
- Built on top of YZhanGateway for flexible API interactions

Requirements
------------

[](#requirements)

- PHP 5.4 or higher
- OpenAI API key
- Composer for dependency management

Installation
------------

[](#installation)

Install YZhanTranslator using Composer:

```
composer require mantoufan/yzhantranslator
```

Usage
-----

[](#usage)

### Basic Translation

[](#basic-translation)

```
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 Translation

[](#json-translation)

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

### Language Detection

[](#language-detection)

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

### Language JSON Detection

[](#language-json-detection)

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

### Custom Prompts

[](#custom-prompts)

```
$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']
```

### Images Descriptions

[](#images-descriptions)

You can now translate images by providing an array of image URLs.
The translator will return descriptions for each image in the specified language.

```
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' => '']]
```

Configuration
-------------

[](#configuration)

YZhanTranslator uses environment variables for configuration. Create a `.env` file in your project root with the following contents:

```
OPENAI_APIKEY=your_openai_api_key
OPENAI_APIURL=https://api.openai.com
OPENAI_ORGANIZATION=your_openai_organization_id

```

Parameters
----------

[](#parameters)

The `translate()` and `detect()` methods accept an optional `$params` array for additional configuration:

- `prompt`: (string) Additional prompt to customize results, e.g., 'do not translate the href attribute'
- `cache`: (array) Caching options
    - `type`: (string) Cache type (default is 'File')
    - `params`: (array) Cache-specific parameters
        - `dir`: (string) Directory for file-based caching
    - `maxAge`: (int) Cache expiration time in seconds
- `timeout`: (int) Request timeout in seconds (default is 6 seconds)

Example usage with parameters:

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

Testing
-------

[](#testing)

Run the test suite using PHPUnit:

```
composer test
```

Generate a code coverage report:

```
composer coverage
```

License
-------

[](#license)

This project is open-sourced software licensed under the MIT license.

Author
------

[](#author)

Shon Wu - [GitHub](https://github.com/mantoufan)

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance42

Moderate activity, may be stable

Popularity15

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~6 days

Recently: every ~28 days

Total

19

Last Release

471d ago

Major Versions

1.1.0 → 2.0.02024-10-05

### Community

Maintainers

![](https://www.gravatar.com/avatar/186219fca45bab5c5266d7c1f22c79c217f21ba7ada3142795a8ae69f95be0f6?d=identicon)[mantoufan](/maintainers/mantoufan)

---

Top Contributors

[![mantoufan](https://avatars.githubusercontent.com/u/4961543?v=4)](https://github.com/mantoufan "mantoufan (25 commits)")

---

Tags

cachedetectorgptjsontranslatertranslationjsoncacheopenaitranslater

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mantoufan-yzhantranslator/health.svg)

```
[![Health](https://phpackages.com/badges/mantoufan-yzhantranslator/health.svg)](https://phpackages.com/packages/mantoufan-yzhantranslator)
```

###  Alternatives

[aplus/cache

Aplus Framework Cache Library

161.6M4](/packages/aplus-cache)[cache/void-adapter

A PSR-6 cache implementation using Void. This implementation supports tags

183.0M44](/packages/cache-void-adapter)[spekkionu/assetcachebuster

Prefixes asset urls with a unique hash which will allow invalidation of asset files cached by the browser.

3243.2k](/packages/spekkionu-assetcachebuster)[ihor/cachalot

Cache a lot in a proper way (APC, XCache, Memcached, Redis, Couchbase)

2528.1k](/packages/ihor-cachalot)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
