[PHP]Try to translate while maintaining html tags with the API of DeepL


The translation service DeepL also provides an API, and although there are some limitations, it is a convenient and useful service that also offers a free framework.

This website also uses the API of DeepL to translate the text and other information.

I recommend the DeepL API because it is free, and you can translate without destroying html tags by specifying the API.

Here is a sample code.

$param = array(
'auth_key' => 'APIKey',
'text' => '<p>雨</p>',.
'target_lang' => 'EN', 'tag_handling' => 'tag_handling' => 'tag_handling'
'tag_handling' => 'xml',.
'source_lang' => 'JA'
);
$curl = curl_init("https://api-free.deepl.com/v2/translate");
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($param));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE)
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$res = curl_exec($curl);
curl_close($curl);

$re = json_decode($res, true);
echo $re["translations"][0]["text"];

First, register with the API site at DeepL to obtain an API key.

Copy and paste that API key into auth_key.

Put the words you want to translate in the text field.

target_lang is the language you want to translate. The above code is set to translate to English.

‘tag_handling’ => ‘xml’ is the setting for handling html.

source_lang is set to the source language of the translation, but it seemed fine without it.

I got stuck on Chinese in target_lang, but it seems to set ZH for simplified Chinese and ZH-HANT for traditional Chinese used in Taiwan and other countries.

Well, that’s all for this time!


Articles of relevance