DeepL PHP Client Library

repository·main·Indexed 42 days ago

https://github.com/deepl/deepl-php

Official PHP client library for the DeepL API, enabling applications to perform high-quality text and document translations. Supports PHP 7.3+ (PHP 8.1+ recommended). Features include text translation via translateText(), document translation with translateDocument(), text rephrasing, multilingual glossary management, and account usage tracking.

Tokens
18.2K
Snippets
57
Records
65
Agent score
54%

What's inside DeepL PHP

  1. How multilingual glossaries work in v3

    main

    In the v3 API, glossaries are no longer limited to a single language pair. Instead, they use the concept of glossary dictionaries.

    • Monolingual Glossaries (v2): A single GlossaryInfo object containing one SourceLanguageCode and one TargetLanguageCode.
    • Multilingual Glossaries (v3): A MultilingualGlossaryInfo object that contains an array of MultilingualGlossaryDictionaryInfo objects. Each dictionary within the glossary specifies its own SourceLang, TargetLang, and its own set of entries.

    To create or manage these, you use MultilingualGlossaryDictionaryEntries to encapsulate a specific language pair and its corresponding entries.

    // Creating a dictionary for a specific language pair
    $entries = GlossaryEntries::fromEntries(['artist' => 'Maler', 'prize' => 'Gewinn']);
    $myGlossaryDict = new MultilingualGlossaryDictionaryEntries('en', 'de', $entries);
    
    // Adding it to a multilingual glossary
    $myGlossary = $deeplClient->createMultilingualGlossary('My glossary', [$myGlossaryDict]);
  2. Export a translation memory

    main

    Export a translation memory to a TMX file using exportTranslationMemoryToFilepath(). This method creates the export job and waits for it to finish before writing the file.

    $job = $deeplClient->exportTranslationMemoryToFilepath('YOUR_TM_ID', '/path/to/exported.tmx');

    Alternatively, you can manage the steps manually:

    1. createTranslationMemoryExport(): Starts the export. If the translation memory hasn't changed, the response may indicate reusedExisting is true.
    2. waitUntilTranslationMemoryJobDone(): Waits for the job to complete.
    3. downloadTranslationMemoryExport(): Writes the exported file to the specified path.
    // High-level
    $job = $deeplClient->exportTranslationMemoryToFilepath('YOUR_TM_ID', '/path/to/exported.tmx');
    
    // Manual steps
    $created = $deeplClient->createTranslationMemoryExport('YOUR_TM_ID');
    $job = $deeplClient->waitUntilTranslationMemoryJobDone($created->jobId);
    $deeplClient->downloadTranslationMemoryExport($job, '/path/to/exported.tmx');
  3. Format and fix code style

    main

    To ensure code adheres to the project's style guidelines, use the following PHP Code Beautifier and Fixer (phpcbf) and PHP Code Sniffer (phpcs) commands located in the vendor directory:

    ./vendor/bin/phpcbf
    ./vendor/bin/phpcs
  4. Use glossaries in text and document translation

    main

    You can apply a stored glossary to translations by providing the glossary option in the options array. When using a glossary, you must specify the sourceLang argument.

    Supported for:

    • translateText()
    • translateDocument()
    • translateDocumentUpload()

    To apply multiple glossaries (up to 5) in a single request, use the glossary_ids option instead of glossary. This must be an array of glossary IDs, GlossaryInfo, or MultilingualGlossaryInfo objects. glossary_ids cannot be combined with the singular glossary option.

    // Using a single glossary
    $withGlossary = $deeplClient->translateText($text, 'en', 'de', ['glossary' => $myGlossary]);
    
    // Using multiple glossaries (up to 5)
    $deeplClient->translateText(
        $text, 'en', 'de', ['glossary_ids' => [$glossaryA, $glossaryB]]
    );
    
    // Using a glossary for document translation
    $deeplClient->translateDocument(
        $inFile, $outFile, 'en', 'de', ['glossary' => $myGlossary]
    );
  5. Import a translation memory

    main

    You can import a TMX file as a new translation memory using two different approaches:

    1. High-level approach

    Use importTranslationMemoryFromFilepath() to handle the entire process: creating the job, uploading the file, and waiting for completion. It returns a TranslationMemoryJob containing the new translationMemoryId.

    $job = $deeplClient->importTranslationMemoryFromFilepath('/path/to/legal.tmx', 'Legal TM', 300);
    echo "Created translation memory {$job->result()->translationMemoryId}\n";

    2. Step-by-step approach

    If you need to upload the file yourself or poll for progress manually, use the granular methods:

    1. createTranslationMemoryImport(): Returns an upload URL and a job ID. The job status will be awaiting_input until the file is uploaded.
    2. uploadTranslationMemoryFile(): Uploads the file content to the provided URL.
    3. waitUntilTranslationMemoryJobDone(): Polls the job status until completion.

    Note: The upload URL is a pre-signed storage URL outside the DeepL API; your authentication key is not sent to it.

    // High-level
    $job = $deeplClient->importTranslationMemoryFromFilepath('/path/to/legal.tmx', 'Legal TM', 300);
    
    // Step-by-step
    $fileContent = file_get_contents('/path/to/legal.tmx');
    $created = $deeplClient->createTranslationMemoryImport('legal.tmx', strlen($fileContent), null, 'Legal TM');
    $deeplClient->uploadTranslationMemoryFile($created, $fileContent);
    $job = $deeplClient->waitUntilTranslationMemoryJobDone($created->jobId, 300);
  6. Identify your application with AppInfo

    main

    To identify your application when making API calls, provide a DeepL\AppInfo object via the app_info option. This is recommended for developers building third-party applications. Both name and version are required.

    Note: If you manually set the User-Agent via the headers option, it will override this setting. In that case, you must manually include your application identification in the User-Agent header.

    $options = ['app_info' => new \DeepL\AppInfo('my-custom-php-chat-client', '1.2.3')];
    $deeplClient = new \DeepL\DeepLClient('YOUR_AUTH_KEY', $options);
  7. Use document minification for large files

    main

    To bypass the 30 MB DeepL API limit for files containing heavy media (like images or videos), you can enable minification. The library extracts the document, replaces large media with tiny placeholders, translates the file, and then re-inserts the original media into the final file.

    Requirements:

    • Requires at least 2x the file size in available temporary disk space.
    • Supported document types: pptx, docx.
    • Supported media types include common formats like png, jpg, mp4, mp3, wav, etc.

    To use it with the high-level method, pass the ENABLE_DOCUMENT_MINIFICATION option:

    $deeplClient->translateDocument(
        $inFile, $outFile, 'en', 'de', [TranslateDocumentOptions::ENABLE_DOCUMENT_MINIFICATION => true]
    );

    For low-level control with uploadDocument(), use the DocumentMinifier class manually.

  8. Run tests for deepl-php

    main

    Execute the test suite using phpunit.

    By default, tests communicate with the real DeepL API using the authentication key provided via the DEEPL_AUTH_KEY environment variable. Note that running tests this way will consume your DeepL API usage quota.

    Alternatively, you can run tests against a mock server (such as deepl-mock) to test error handling without consuming API quota. To use a mock server, run it in a separate terminal and define the following environment variables when running phpunit:

    • DEEPL_MOCK_SERVER_PORT: The port where the mock server is running.
    • DEEPL_SERVER_URL: The URL of the mock server.
    # Running tests with real API (requires DEEPL_AUTH_KEY)
    phpunit
    
    # Running tests with a mock server
    DEEPL_MOCK_SERVER_PORT=8080 DEEPL_SERVER_URL=http://localhost:8080 phpunit
  9. Get a DeepL API authentication key

    main
    To use the library, you must have a DeepL API authentication key. You can create an account to obtain a key. A DeepL API Free account allows for up to 500,000 characters of translation per month at no cost.
  10. Create multilingual glossaries

    main

    Multilingual glossaries (v3 API) allow you to define custom terms for specific language pairs.

    Using GlossaryEntries

    Create entries using GlossaryEntries::fromEntries() with an associative array where keys are source terms and values are target terms.

    Creating from objects

    1. Create GlossaryEntries.
    2. Wrap them in a MultilingualGlossaryDictionaryEntries object specifying the source and target languages.
    3. Pass an array of these dictionary objects to createMultilingualGlossary().
    $entries = GlossaryEntries::fromEntries(['artist' => 'Maler', 'prize' => 'Gewinn']);
    $myGlossaryDict = new MultilingualGlossaryDictionaryEntries('en', 'de', $entries);
    $myGlossary = $deeplClient->createMultilingualGlossary('My glossary', [$myGlossaryDict]);

    Creating from CSV

    Use createMultilingualGlossaryFromCsv() to upload a glossary from a CSV string.

    $csvData = file_get_contents('/path/to/glossary_file.csv');
    $myCsvGlossary = $deeplClient->createMultilingualGlossaryFromCsv(
        'CSV glossary',
        'en',
        'de',
        $csvData,
    );
    // Create an English to German glossary with two terms:
    $entries = GlossaryEntries::fromEntries(['artist' => 'Maler', 'prize' => 'Gewinn']);
    $myGlossaryDict = new MultilingualGlossaryDictionaryEntries('en', 'de', $entries);
    $myGlossary = $deeplClient->createMultilingualGlossary('My glossary', [$myGlossaryDict]);
  11. Manage Style Rules

    main

    Style rules allow you to customize translations with managed, shared rules for style and formatting.

    Core Operations:

    • Create: createStyleRule($name, $language, $configuredRules = [], $customInstructions = []).
    • Retrieve: getStyleRule($idOrObject).
    • List: getAllStyleRules(page: 0, pageSize: 10, detailed: false).
    • Update: updateStyleRuleName($styleRule, $newName) and updateStyleRuleConfiguredRules($styleRule, $rules).
    • Delete: deleteStyleRule($styleRule).

    Custom Instructions: You can manage free-text prompts within a rule using createStyleRuleCustomInstruction(), getStyleRuleCustomInstruction(), updateStyleRuleCustomInstruction(), and deleteStyleRuleCustomInstruction().

    Using Style Rules: Pass the style_id option (containing an ID or StyleRuleInfo object) to translateText() or translateDocument().

    // Create a rule with custom instructions
    $styleRule = $deeplClient->createStyleRule(
        'Formal English',
        'en',
        ['style_and_tone' => ['formal_informal' => 'formal']],
        [['label' => 'Formality', 'prompt' => 'Always use formal language']]
    );
    
    // Use the rule in translation
    $result = $deeplClient->translateText(
        'Hello, world!',
        'en',
        'de',
        ['style_id' => $styleRule]
    );