Download the PHP package deeplcom/deepl-php without Composer

On this page you can find all versions of the php package deeplcom/deepl-php. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package deepl-php

deepl-php

Latest Stable Version Minimum PHP version License: MIT

Official PHP client library for the DeepL API.

The DeepL API is a language translation API that allows other computer programs to send texts and documents to DeepL's servers and receive high-quality translations. This opens a whole universe of opportunities for developers: any translation product you can imagine can now be built on top of DeepL's best-in-class translation technology.

The DeepL PHP library offers a convenient way for applications written for PHP to interact with the DeepL API. We intend to support all API functions with the library, though support for new features may be added to the library after they’re added to the API.

Getting an authentication key

To use deepl-php, you'll need an API authentication key. To get a key, please create an account here. With a DeepL API Free account you can translate up to 500,000 characters/month for free.

Installation

To use this library in your project, install it using Composer:

Requirements

The library officially supports PHP 7.3 and later.

Starting in 2024, we will drop support for older PHP versions that have reached official end-of-life. You can find the PHP versions and support timelines here. To continue using this library, you should update to PHP 8.1+.

Usage

Construct a DeepLClient object. The first argument is a string containing your API authentication key as found in your DeepL Pro Account.

Be careful not to expose your key, for example when sharing source code.

DeepLClient accepts options as the second argument, see Configuration for more information.

Translating text

To translate text, call translateText(). The first argument is a string containing the text you want to translate, or an array of strings if you want to translate multiple texts.

The second and third arguments are the source and target language codes. Language codes are case-insensitive strings according to ISO 639-1, for example 'de', 'fr', 'ja''. Some target languages also include the regional variant according to ISO 3166-1, for example 'en-US', or 'pt-BR'. The source language also accepts null, to enable auto-detection of the source language.

The last argument to translateText() is optional, and specifies extra translation options, see Text translation options below.

translateText() returns a TextResult, or an array of TextResults corresponding to your input text(s). TextResult has the following properties:

Text translation options

Provide options to the translateText function as an associative array, using the following keys:

The following options are only used if tag_handling is 'xml':

The TranslateTextOptions class defines constants for the options above, for example TranslateTextOptions::FORMALITY is defined as 'formality'.

Rephrasing text

To rephrase text, call rephraseText(). The first argument is a string containing the text you want to rephrase, or an array of strings if you want to rephrase multiple texts.

The second argument is the target language code, which is optional. If not provided, the text will be rephrased in its original language.

The last argument is optional and specifies extra rephrasing options, see Rephrasing options below.

rephraseText() returns a RephraseTextResult, or an array of RephraseTextResults corresponding to your input text(s), similar to translateText().

Rephrasing options

Provide options to the rephraseText function as an associative array, using the following keys:

Note: Currently, you can only specify either a style OR a tone, not both at the same time.

The DeepLClientOptions class defines constants for these options:

Translating documents

To translate documents, call translateDocument(). The first and second arguments are the input and output file paths.

The third and fourth arguments are the source and target language codes, and they work exactly the same as when translating text with translateText().

The last argument to translateDocument() is optional, and specifies extra translation options, see Document translation options below.

translateDocument() wraps multiple API calls: uploading, polling status until the translation is complete, and downloading. If your application needs to execute these steps individually, you can instead use the following functions directly:

Document translation options

Provide options to the translateDocument function as an associative array, using the following keys:

The uploadDocument function also supports these options.

The TranslateDocumentOptions class defines constants for the options above, for example TranslateDocumentOptions::FORMALITY is defined as 'formality'.

Document minification

In some contexts, one can end up with large document files (e.g. PowerPoint presentations or Word files with many contributors, especially in a larger organization). However, the DeepL API enforces a limit of 30 MB for most of these files (see Usage Limits in the docs). In the case that most of this size comes from media included in the documents (e.g. images, videos, animations), document minification can help. In this case, the library will create a temporary directory to extract the document into, replace the large media with tiny placeholders, create a minified document, translate that via the API, and re-insert the original media into the original file. Please note that this requires a bit of additional (temporary) disk space, we recommend at least 2x the file size of the document to be translated.

To use document minification, simply pass the option to the translateDocument function:

In order to use document minification with the lower-level uploadDocument, waitUntilDocumentTranslationComplete and downloadDocument methods as well as other details, see the DocumentMinifier class.

Currently supported document types for minification:

  1. pptx
  2. docx

Currently supported media types for minification:

  1. png
  2. jpg
  3. jpeg
  4. emf
  5. bmp
  6. tiff
  7. wdp
  8. svg
  9. gif
  10. mp4
  11. asf
  12. avi
  13. m4v
  14. mpg
  15. mpeg
  16. wmv
  17. mov
  18. aiff
  19. au
  20. mid
  21. midi
  22. mp3
  23. m4a
  24. wav
  25. wma

Glossaries

Glossaries allow you to customize your translations using user-defined terms. Multiple glossaries can be stored with your account, each with a user-specified name and a uniquely-assigned ID.

v2 versus v3 glossary APIs

The newest version of the glossary APIs are the /v3 endpoints, allowing both editing functionality plus support for multilingual glossaries. New methods and objects have been created to support interacting with these new glossaries. Due to this new functionality, users are recommended to utilize these multilingual glossary methods. However, to continue using the v2 glossary API endpoints, please continue to use the existing endpoints in the Translator.php (e.g. createGlossary(), getGlossary(), etc).

To migrate to use the new multilingual glossary methods from the current monolingual glossary methods, please refer to this migration guide.

The following sections describe how to interact with multilingual glossaries using the new functionality:

Creating a glossary

You can create a glossary with your desired terms and name using createMultilingualGlossary(). ach glossary contains a list of dictionaries, where each dictionary applies to a single source-target language pair. Note: Glossaries are only supported for some language pairs, see Listing available glossary languages for more information. The entries should be specified as a GlossaryEntries object; you can create one using GlossaryEntries::fromEntries using an associative array with the source terms as keys and the target terms as values.

Then use createMultilingualGlossary() with the glossary name, and its list of dictionaries. Each dictionary should have source and target language codes and the GlossaryEntries. If successful, the glossary is created and stored with your DeepL account, and a MultilingualGlossaryInfo object is returned including the ID, name, languages and entry count.

You can also upload a glossary downloaded from the DeepL website using createMultilingualGlossaryFromCsv(). Specify the glossary name, and source and target language codes, and instead of specifying the terms as an associative array, specify the CSV data as a string:

The API documentation explains the expected CSV format in detail.

Getting, listing and deleting stored glossaries

Functions to get, list, and delete stored glossaries are also provided:

Listing entries in a stored glossary

The MultilingualGlossaryDictionaryInfo object does not contain the glossary entries, but instead only the number of entries in the entryCount property.

To list the entries contained within a stored glossary, use getMultilingualGlossaryEntries() providing either the MultilingualGlossaryInfo object or glossary ID and either a MultilingualGlossaryDictionaryInfo or source and target language pair:

Editing a glossary

Functions to edit stored glossaries are also provided:

Using a stored glossary

You can use a stored glossary for text translation by setting the glossary option to either the glossary ID or MultilingualGlossaryInfo object. You must also specify the sourceLang argument (it is required when using a glossary):

Using a stored glossary for document translation is the same: set the glossary option. The sourceLang argument must also be specified:

The translateDocument() and translateDocumentUpload() functions both support the glossary argument.

To apply multiple glossaries (up to 5) in a single request, use the glossary_ids option instead of glossary, for both text and document translation. Set it to an array of glossary IDs, GlossaryInfo, or MultilingualGlossaryInfo objects. The sourceLang argument is required, and glossary_ids cannot be combined with the singular glossary option:

Checking account usage

To check account usage, use the getUsage() function.

The returned Usage object contains up to three usage subtypes, depending on your account type: character, document and teamDocument. For API accounts character will be set, the others null.

Each usage subtypes (if set) have count and limit properties giving the amount used and maximum amount respectively, and the limitReached() function that checks if the usage has reached the limit. The top level Usage object has the anyLimitReached() function to check all usage subtypes.

Listing available languages

You can request the list of languages supported by DeepL API for text and documents using the getSourceLanguages() and getTargetLanguages() functions. They both return an array of Language objects.

The name property gives the name of the language in English, and the code property gives the language code. The supportsFormality property only appears for target languages, and is a bool indicating whether the target language supports the optional formality parameter.

Listing per-resource language support

getLanguagesForResource() queries the languages supported for a given DeepL resource (text translation, document translation, glossaries, voice, write, style rules), together with per-feature support information. It covers newer languages and features than getSourceLanguages() / getTargetLanguages(), and returns a single list per resource in which each LanguageSupport exposes usableAsSource and usableAsTarget flags.

To discover which features each resource exposes (and whether a feature needs source/target language support), use getLanguageResources():

Listing available glossary languages

Glossaries are supported for a subset of language pairs. To retrieve those languages use the getGlossaryLanguages() function, which returns an array of GlossaryLanguagePair objects. Each has sourceLang and targetLang properties indicating that that pair of language codes is supported.

You can also find the list of supported glossary language pairs in the API documentation.

Note that glossaries work for all target regional-variants: a glossary for the target language English ('en') supports translations to both American English ('en-US') and British English ('en-GB').

Style Rules

Style rules allow you to customize your translations using a managed, shared list of rules for style, formatting, and more. Multiple style rules can be stored with your account, each with a user-specified name and a uniquely-assigned ID.

Creating a style rule

Use createStyleRule() to create a new style rule with a name and language. You can optionally pass configured rules and custom instructions:

Getting a style rule

Use getStyleRule() to retrieve a single style rule by its ID or a StyleRuleInfo object:

Listing all style rules

getAllStyleRules() returns a list of StyleRuleInfo objects corresponding to all of your stored style rules. The method accepts optional parameters: page (page number for pagination, 0-indexed), pageSize (number of items per page), and detailed (whether to include detailed configuration rules in the configuredRules property).

Updating a style rule

Use updateStyleRuleName() to rename a style rule, and updateStyleRuleConfiguredRules() to replace the configured rules:

Deleting a style rule

Use deleteStyleRule() to delete a style rule:

Managing custom instructions

Custom instructions allow you to add free-text prompts to a style rule. Use the custom instruction methods to create, get, update, and delete them:

Using a stored style rule

You can use a stored style rule for text translation by setting the style_id option to either the style rule ID or a StyleRuleInfo object:

Style rules are also supported for document translation. Set the style_id option on translateDocument() (or uploadDocument()) in the same way:

Translation Memories

Translation memories allow you to leverage previously translated segments to improve consistency and efficiency. Translation memories are managed on your account, each with a user-specified name and a uniquely-assigned ID.

Translation memories can also be uploaded and managed in the DeepL UI via https://www.deepl.com/translation-memory.

Listing all translation memories

listTranslationMemories() returns a list of TranslationMemoryInfo objects corresponding to all of your stored translation memories. The method accepts optional parameters: page (page number for pagination, 0-indexed) and pageSize (number of items per page).

Getting a translation memory

Use getTranslationMemory() to retrieve a single translation memory by its ID or a TranslationMemoryInfo object:

Listing the segments of a translation memory

listTranslationMemorySegments() returns one page of segments as a TranslationMemorySegments object. Pagination is cursor-based: omit page_cursor on the first call, then pass the previous response's nextPageCursor until it is null. Optionally filter with filter_text (at least 2 characters, matched against both source and target text) and filter_case_sensitive. Note that segmentCount is the translation-memory total and is not reduced by the filter.

Importing a translation memory

importTranslationMemoryFromFilepath() imports a TMX file as a new translation memory: it creates the import job, uploads the file, and waits for processing to finish. The returned TranslationMemoryJob carries the ID of the new translation memory. An import usually takes under a minute; the optional third argument is a maximum time in seconds to wait for it.

The three steps are also available separately, for example to upload the file yourself or to poll for progress. createTranslationMemoryImport() returns an upload URL that the file must be uploaded to before processing starts, then getTranslationMemoryJob() reports the status. Note that the upload URL is a pre-signed storage URL outside the DeepL API, so your authentication key is not sent to it.

Note that the job keeps reporting 'awaiting_input' for a while after the file has been uploaded, because the API detects the upload asynchronously. waitUntilTranslationMemoryJobDone() polls through that status like any other non-terminal one. A job whose file is never uploaded does not finish on its own, so pass a timeout in seconds as the second argument when that is a possibility.

Exporting a translation memory

exportTranslationMemoryToFilepath() exports a translation memory to a TMX file: it creates the export job, waits for it to finish, and writes the result.

As with import, the individual steps are available separately. Note that the API may reuse a previously completed export of an unchanged translation memory, indicated by reusedExisting.

Deleting a translation memory

Use deleteTranslationMemory() to delete a translation memory by its ID or a TranslationMemoryInfo object:

Using a translation memory for translation

You can use a translation memory for text translation by setting the translation_memory_id option to either the translation memory ID or a TranslationMemoryInfo object. Optionally, set translation_memory_threshold to control the minimum similarity score for matches:

Translation memories are also supported for document translation. Set the translation_memory_id (and optionally translation_memory_threshold) option on translateDocument() (or uploadDocument()) in the same way:

Writing a Plugin

If you use this library in an application, please identify the application with the app_info DeeplClientOption, which needs the name and version of the app:

This information is passed along when the library makes calls to the DeepL API. Both name and version are required. Please note that setting the User-Agent header via the headers DeeplClientOption will override this setting, if you need to use this, please manually identify your Application in the User-Agent header.

Configuration

The DeepLClient constructor accepts configuration options as a second argument, for example:

Provide the options as an associative array with the following keys:

The DeepLClientOptions class defines constants for the options above.

Proxy configuration

You can configure a proxy using the proxy option when constructing a DeepLClient:

The proxy option is used for the CURLOPT_PROXY option when preparing the cURL request, see the documentation for cURL.

Logging

To enable logging, specify a PSR-3 compatible logger as the 'logger' option in the DeepLClient configuration options.

Anonymous platform information

By default, we send some basic information about the platform the client library is running on with each request, see here for an explanation. This data is completely anonymous and only used to improve our product, not track any individual users. If you do not wish to send this data, you can opt-out when creating your DeepLClient object by setting the send_platform_info flag in the options like so:

You can also customize the User-Agent header completely by setting its value explicitly in the options via the headers field (this overrides the send_platform_info option). For example::

Custom HTTP client

If you want to set specific HTTP options that we don't expose (or otherwise want more control over the API calls by the library), you can configure the library to use a PSR-18 compliant HTTP client of your choosing. For example, in order to use a connect timeout of 5.2 seconds and read timeout of 7.4 seconds while using a proxy with Guzzle:

Request retries

Requests to the DeepL API that fail due to transient conditions (for example, network timeouts or high server-load) will be retried. The maximum number of retries can be configured when constructing the DeepLClient object using the max_retries option. The timeout for each request attempt may be controlled using the timeout option. An exponential-backoff strategy is used, so requests that fail multiple times will incur delays.

Issues

If you experience problems using the library, or would like to request a new feature, please open an issue.

Development

We welcome Pull Requests, please read the contributing guidelines.

Tests

Execute the tests using phpunit. The tests communicate with the DeepL API using the auth key defined by the DEEPL_AUTH_KEY environment variable.

Be aware that the tests make DeepL API requests that contribute toward your API usage.

The test suite may instead be configured to communicate with the mock-server provided by deepl-mock. Although most test cases work for either, some test cases work only with the DeepL API or the mock-server and will be otherwise skipped. The test cases that require the mock-server trigger server errors and test the client error-handling. To execute the tests using deepl-mock, run it in another terminal while executing the tests. Execute the tests using phpunit with the DEEPL_MOCK_SERVER_PORT and DEEPL_SERVER_URL environment variables defined referring to the mock-server.

Formatting and fixing code

For formatting and fixing code style issues, run this command:


All versions of deepl-php with dependencies

PHP Build Version
Package Version
Requires php Version >=7.3.0
psr/log Version ^1.1 || ^2.0 || ^3.0
psr/http-client Version ^1.0
php-http/discovery Version ^1.18
ext-json Version *
ext-curl Version *
ext-mbstring Version *
psr/http-client-implementation Version *
psr/http-factory-implementation Version *
php-http/multipart-stream-builder Version ^1.3
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package deeplcom/deepl-php contains the following files

Loading the files please wait ...