Search by

PHP client library for the DB Translations API - translate text across 30+ languages with pre-translated strings and DeepL integration

v1.0.0 2026-11-15 05:06 UTC

This package is auto-updated.

Last update: 2026-11-15 05:42:02 UTC


README

PHP client library for the DB Translations API - translate text across 30+ languages with pre-translated strings and DeepL integration.

Installation

Install the SDK via Composer:

composer require php-translations/client

Not yet on Packagist? Install straight from GitHub until it is listed:

composer config repositories.translations-api git https://github.com/stephenhodgkiss/translations-api-php.git
composer require php-translations/client:dev-main

Or add to your composer.json:

{
    "require": {
        "php-translations/client": "^1.0"
    }
}

Quick Start

require_once 'vendor/autoload.php';

use PHPTranslations\Client;

// Initialize the client with your API key
$client = new Client('your-api-key-here', 'https://translationsapi.com/api/v1');

// Translate text
$translation = $client->translate('Welcome to our application', 'es');
echo $translation; // "Bienvenido a nuestra aplicación"

API Reference

Constructor

$client = new Client(
    string $apiKey,           // Your API key from the customer portal
    string $apiBaseUrl = 'https://translationsapi.com/api/v1',  // API base URL
    int $timeout = 30        // Request timeout in seconds
);

Methods

translate(string $text, string $language, bool $useDeepl = false): string

Translate text to a target language.

  • $text: The text to translate
  • $language: Target language code (e.g., 'es', 'de', 'fr')
  • $useDeepl: Whether to use DeepL for auto-translation (default: false)
  • Returns: The translated text
$translation = $client->translate('Hello', 'es');

exists(string $text): bool

Check if a source string exists in the database.

  • $text: The text to check
  • Returns: True if the string exists, false otherwise
if ($client->exists('Hello')) {
    echo 'String exists in database';
}

translateOrAdd(string $text, string $language, bool $useDeepl = true): string

Translate text or add it as a new source string. This method:

  1. Returns existing translation if available
  2. Uses DeepL to auto-translate if enabled and string is new
  3. Adds the source string and translation to the database
  • $text: The text to translate
  • $language: Target language code
  • $useDeepl: Whether to use DeepL for auto-translation (default: true)
  • Returns: The translated text
$translation = $client->translateOrAdd('New feature', 'fr', true);

batch(array $texts, array $languages, bool $useDeepl = false): array

Batch translate multiple texts to multiple languages.

  • $texts: Array of texts to translate (max 100)
  • $languages: Array of language codes (max 10)
  • $useDeepl: Whether to use DeepL for auto-translation (default: false)
  • Returns: Nested array with translations: [text_index][language_code] => translation
$texts = ['Login', 'Register', 'Dashboard'];
$languages = ['es', 'de', 'fr'];

$results = $client->batch($texts, $languages);

echo $results[0]['es']; // Spanish translation of 'Login'

usage(): array

Get current usage statistics.

  • Returns: Array with subscription, plan, usage, and limits data
$usage = $client->usage();

echo "API Calls: {$usage['usage']['api_calls']} / {$usage['limits']['api_calls']}\n";
echo "DeepL Calls: {$usage['usage']['deepl_calls']} / {$usage['limits']['deepl_calls']}\n";

dictionary(string $language, ?string $module = null): array

Load all translations for a language as a key-value dictionary. Ideal for caching on your server and using throughout page rendering.

  • $language: Target language code (e.g., 'es', 'de', 'fr')
  • $module: Optional module filter (e.g., 'common', 'yempay'). If omitted, returns all translations for that language.
  • Returns: Array with language, module, count, last_updated, etag, and translations (key-value map)
  • Counts as: 1 API call regardless of translation count
// Load all Spanish translations for the common module
$dict = $client->dictionary('es', 'common');

echo $dict['translations']['Welcome']; // → "Bienvenido"
echo $dict['translations']['Login'];   // → "Iniciar sesión"
echo "Total: {$dict['count']} strings\n"; // → "Total: 981 strings"

Custom Translation Methods (Professional+ Only)

These methods allow Professional and Enterprise subscribers to manage their own custom translation pool.

uploadFile(string $filePath, ?string $format = null): array

Upload a file of source strings or translations. Supports TXT, CSV, and JSON formats.

  • $filePath: Path to the file to upload
  • $format: Optional file format ('txt', 'csv', 'json'). Auto-detected from extension if null.
  • Returns: Upload result with stats (strings_added, translations_added, strings_skipped, etc.)
// Upload a CSV file with source and translations
$result = $client->uploadFile('/path/to/my-translations.csv');

echo "Added: {$result['strings_added']} strings\n";
echo "Translations: {$result['translations_added']}\n";
echo "Skipped (common library): {$result['strings_skipped_common']}\n";

Supported File Formats:

  • TXT: One English string per line

    Welcome to MyApp
    Dashboard
    Settings
    
  • CSV: Source + translations (first row is header)

    source,en,es,fr
    Welcome,Welcome,Bienvenido,Bienvenue
    Settings,Settings,Configuración,Paramètres
  • JSON: Structured translations

    {
      "strings": {
        "Welcome": {"es": "Bienvenido", "fr": "Bienvenue"},
        "Settings": {"es": "Configuración", "fr": "Paramètres"}
      }
    }

uploadStrings(array $strings, bool $autoTranslate = false): array

Upload source strings as a JSON array in the request body.

  • $strings: Array of source strings to upload
  • $autoTranslate: Whether to auto-translate missing strings (default: false)
  • Returns: Upload result with stats
// Upload strings without auto-translation
$result = $client->uploadStrings([
    'My Dashboard',
    'Custom Feature',
    'User Profile'
]);

// Upload with auto-translation enabled
$result = $client->uploadStrings([
    'My Dashboard',
    'Custom Feature'
], true);

getMyStrings(int $page = 1, int $perPage = 100): array

Get the subscriber's custom source strings with pagination.

  • $page: Page number (default: 1)
  • $perPage: Items per page (default: 100)
  • Returns: Paginated list of custom strings
// Get first page of custom strings
$strings = $client->getMyStrings();

foreach ($strings['strings'] as $string) {
    echo "{$string['text']} ({$string['translations_count']} translations)\n";
}

echo "Total: {$strings['total']} strings\n";

deleteString(int $stringId): bool

Delete a custom source string and all its translations.

  • $stringId: The ID of the source string to delete
  • Returns: True on success
// Delete a custom string by ID
$client->deleteString(123);

getMyStats(): array

Get subscriber translation statistics including custom strings, limits, and usage.

  • Returns: Statistics array
$stats = $client->getMyStats();

echo "Custom strings: {$stats['custom_strings']} / {$stats['custom_strings_limit']}\n";
echo "Uploads this month: {$stats['uploads_this_month']} / {$stats['uploads_limit']}\n";
echo "Common library hits: {$stats['common_library_hits']}\n";
echo "DeepL calls saved: {$stats['deepl_calls_saved']}\n";

dictionaryCached(string $language, ?string $module, string $cacheFile, int $ttl = 86400): array

Load dictionary with automatic file caching. Returns cached version if still valid.

  • $language: Target language code
  • $module: Optional module filter
  • $cacheFile: Path to cache file
  • $ttl: Cache time-to-live in seconds (default: 86400 = 24 hours)
  • Returns: Just the translations key-value map
// Load with 24-hour file cache
$translations = $client->dictionaryCached('es', 'common', '/tmp/translations_es_common.json');

echo $translations['Welcome']; // → "Bienvenido"

Helper Methods

getLastResponse(): ?array

Get the last response from the API.

$response = $client->getLastResponse();

getLastStatusCode(): ?int

Get the last HTTP status code.

$statusCode = $client->getLastStatusCode();

setApiBaseUrl(string $apiBaseUrl): self

Set the API base URL.

$client->setApiBaseUrl('https://api.dbtranslations.com/v1');

setTimeout(int $timeout): self

Set the request timeout.

$client->setTimeout(60);

Exception Handling

The SDK throws two types of exceptions:

ClientException

Thrown for general API errors, authentication failures, or invalid requests.

try {
    $translation = $client->translate('Hello', 'es');
} catch (ClientException $e) {
    echo "Error: " . $e->getMessage();
    echo "Status Code: " . $e->getCode();
}

RateLimitException

Thrown when rate limits are exceeded. Includes additional methods to get limit details.

try {
    $translation = $client->translate('Hello', 'es');
} catch (RateLimitException $e) {
    echo "Rate limit exceeded!\n";
    echo "Limit: " . $e->getLimit() . "\n";
    echo "Remaining: " . $e->getRemaining() . "\n";
    echo "Reset at: " . $e->getReset() . "\n";
}

Supported Languages

The SDK supports 30+ languages including:

  • English (en)
  • Spanish (es)
  • French (fr)
  • German (de)
  • Italian (it)
  • Portuguese (pt)
  • Dutch (nl)
  • Russian (ru)
  • Chinese (zh)
  • Japanese (ja)
  • Korean (ko)
  • Arabic (ar)
  • And many more...

See the customer portal for the complete list.

Rate Limits

Rate limits are enforced based on your subscription plan:

Plan API Calls DeepL Calls Custom Strings Uploads/mo Modules
Free 1,000/month 50/month 0 0 1
Starter 10,000/month 500/month 0 0 5
Professional 100,000/month 5,000/month 5,000 25 50
Enterprise Unlimited Unlimited Unlimited Unlimited Unlimited

The SDK automatically handles rate limit headers and throws RateLimitException when limits are exceeded.

Custom Translation Features

Custom translations allow Professional+ subscribers to:

  • Upload their own English source strings and pre-translated files
  • Leverage the common library to save on DeepL costs
  • Manage translations through the portal or SDK

The 3-tier lookup system automatically checks:

  1. Level 1: Your custom translation pool
  2. Level 2: Common library (37,000+ strings across 30 languages)
  3. Level 3: DeepL API (if auto-translate is enabled)

This means you only pay for DeepL calls when a translation isn't available in your custom pool or the common library.

Examples

See the examples/ directory for complete usage examples:

  • basic-usage.php - Simple translation example
  • advanced-usage.php - Advanced features and error handling

Requirements

  • PHP 8.1 or higher
  • cURL extension
  • JSON extension

License

MIT License - see LICENSE file for details.

Support

For support, visit the customer portal or contact support@dbtranslations.com.