Translate text with PHP and Yandex

How to translate texts of any length with the free service offered by the search engine Russian

We are in 2020, and came to the conclusion that if you want to have a blog, or any site on the internet, this must be able to communicate with anyone, seeing that it can fall to the eye of any internet user, whatever part of the globe.

We already gave a look on how to create a website with a useful basis on which to be able to translate into any language, or dialect, easily, going to parameterize the writing through of the file dedicated to the language that we care to use.

In this article we are going to use a procedure, in PHP, that allows us to be able to translate instantly any text in any language, this is to make way of communicating with anyone.

The first thing we need to do is find an online service that allows you to translate a text from any language. Excluding the Google Translator, because for a fee, have relapsed on the API of Yandex, to full free use. The only thing we have to do is obtain a token by registering an account.

Register an account on Yandex Translate

  • We go on Yandex Translate API to perform registration of an account
  • Then in the menu API keys, select the command Create new key
  • By filling out a form that will ask you for the description of our tokens, there will be provided a key which we can use in our PHP code

We integrate Yandex Translate in our PHP code

To put in our PHP code the following function is going to enter the API key you just obtained in place of API KEY

function translatetext($text, $from, $to) {
if (isset($text) && $text!="") {
$api = 'API KEY';
$url = file_get_contents('https://translate.yandex.net/api/v1.5/tr.json/translate?key='.$api.'&lang='.$from.'-'.$to.'&text='.urlencode($text));
$json = json_decode($url);
return $json->text[0];
} else {
return "";
}
}

Using the function translatetext, defining the text to be translated, the source language and the destination, there will be returned a string, which will coincide with the translation of the entered text.

It is important to point out that to run the procedure, it is essential to know what is the language of origin and that of destination, because the function is not able to automatically detect what is the language that we’re translating.

We periodically check the functioning of the links in our articles. If you notice any links that do not work, please let us know in the comments. If you enjoyed the article consider supporting the blog with a small donation. Thank you. Patreon / Ko-fi / Liberapay / Paypal

Leave a Reply

Your email address will not be published. Required fields are marked *