版本 3 已经发布,支持版本 2 直到 2019 年 4 月 30 日。
随着第 3 版的全面发布,现有的第 2 版将于 5 月 1 日起弃用。在04/30/2019 之前,V2 将一直受到支持。
因此,api v3 的示例 PHP/cURL 代码
<?php
$key = "KEY_1"; // secret key here !!!
$host = "https://api.cognitive.microsofttranslator.com";
$path = "/translate?api-version=3.0";
$params = "&to=en&from=ar";
$text = "Hello, world!";
$requestBody = array (
array (
'Text' => $text,
),
);
$content = json_encode($requestBody);
if (!function_exists('com_create_guid')) {
function com_create_guid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
}
$curl_headers = array(
'Content-type: application/json',
'Content-length: '. strlen($content) ,
'Ocp-Apim-Subscription-Key: '. $key ,
'X-ClientTraceId: '. com_create_guid()
);
$url = $host . $path . $params;
$ch = curl_init();
$curl_content = array('content',$content);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close ($ch);
// Note: We convert result, which is JSON, to and from an object so we can pretty-print it.
// We want to avoid escaping any Unicode characters that result contains. See:
// http://php.net/manual/en/function.json-encode.php
$json = json_encode(json_decode($result), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo $json;