Quite often, websites have several languages. In this article, I will describe how to translate text using the DeepL API for automatic text translation.
Here we will describe a method that doesn’t involve the use of plugins or third-party libraries. Clear code using cURL PHP. This method is suitable for both WordPress developers and clear PHP sites.
How to translate text with DeepL API?
You need DeepL account with Free or Pro plan.
You can see the difference between the plans in the following screenshot. Prices and tariffs are current at the time of publication.
You can check the current plans and the list of countries where the DeepL API works by following the link.
Create a translation function
Let’s create a function that sends a request to DeepL and returns a translated text in the selected language.
Let this be a deepLWG function that accepts the parameters text and lang.
Text – is the actual text you want to translate. Lang – is the language you want to translate the text into.
$key – is your key to the DeepL API. You receive it after registering your account. Depending on whether you have a Pro or Free plan, you specify the appropriate url. This is for the Pro version:
Checks, using a ternary operator, whether we received the translated text in response. If so, the function returns it, and if not, it returns the previously sent untranslated text.
Leave a Reply