添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
$subscription_key = 'mykey';
$endpoint = 'https://api.cognitive.microsofttranslator.com';
$path = "/translate?api-version=3.0";

// Translate to German and Italian.
$params = "&to=de&to=it";

$text = "Hello, world!";

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 )

function Translate ($host, $path, $key, $params, $content) {

$headers = "Content-type: application/json\r\n" .
    "Content-length: " . strlen($content) . "\r\n" .
    "Ocp-Apim-Subscription-Key: $key\r\n" .
    "X-ClientTraceId: " . com_create_guid() . "\r\n";
// NOTE: Use the key 'http' even if you are making an HTTPS request. See:
// http://php.net/manual/en/function.stream-context-create.php
$options = array (
    'http' => array (
        'header' => $headers,
        'method' => 'POST',
        'content' => $content
$context  = stream_context_create ($options);
$result = file_get_contents ($host . $path . $params, false, $context);
return $result;

$requestBody = array (
array (
'Text' => $text,
$content = json_encode($requestBody);

$result = Translate ($endpoint, $path, $subscription_key, $params, $content);

// 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;"

what we have:

Warning: file_get_contents(https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=de&to=it): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in
line with $result = Translate ($endpoint, $path, $subscription_key, $params, $content);

what is wrong?
thankl you)

@Serhii Rohatin (MINDTREE LIMITED) I think the region might also be required in the header for this version. Please check this updated post on SO for a similar error.
Please try to add the following header too and check if this works.

'Ocp-Apim-Subscription-Region: '. $location, // LOCATION