This is a drop-in PHP helper class that can translate a bundle of strings, which may contain markup. It uses DeepL's XML translation feature, and is designed to be very easy to use.
Simply require the package in your project via Composer:
"require": {
"mistralys/deepl-xml-translator" : "dev-master"
}See the packagist page: https://packagist.org/packages/mistralys/deepl-xml-translator
$translator = new \DeeplXML\Translator(
'YourAPIKey', // the DeepL API key to use to connect
'EN', // source language
'DE' // target language
); $translator->addString('string1', 'Please translate me');
$translator->addString('string2', 'Please also translate me');try
{
$translator->translate();
}
catch(\DeeplXML\Translator_Exception $e)
{
// handle errors
} Retrieving all strings at once:
$strings = $translator->getStrings();
foreach($strings as $string)
{
$text = $string->getTranslatedText();
}Retrieving specific strings by ID:
$string = $translator->getStringByID('string2');
$text = $string->getTranslatedText();To avoid parts of strings being translated, the characters to ignore can be specified as needed. They are replaced by placeholders by a simple search & replace before sending the translation to DeepL, and restored again afterwards.
$string = $translator->addString('string1', 'Please ignore me');
// the text "ignore" will not be translated in the string
$string->addIgnoreString('ignore');The translator class uses the SC-Networks/deepl-api-connector DeepL API package to connect to the service in the background.
If you need more advanced features, like translating files and the like, you may use the fully configured connector instance directly:
$api = $translator->getConnector();
// do something with itBy default, the unit tests will only test the offline API of the Translator itself. To enable live testing with the DeepL API, rename the file tests/apikey.dist.php to tests/apikey.php and edit it to insert your API key. The additional tests will be enabled automatically.
For free API keys (ending in :fx)
curl -s "https://api-free.deepl.com/v2/usage" \
-H "Authorization: DeepL-Auth-Key YOUR_API_KEY_HERE"For paid API keys
curl -s "https://api.deepl.com/v2/usage" \
-H "Authorization: DeepL-Auth-Key YOUR_API_KEY"With a proxy
curl -x "http://user:pass@proxy:3128" \
-H "Authorization: DeepL-Auth-Key YOUR_API_KEY" \
"https://api.deepl.com/v2/usage"A successful response looks like:
{
"character_count":1234,
"character_limit":500000
}