Microsoft переводчик Azure возвращают ноль с PHP API

Вывод нулевой, версия PHP 5.6. Я добавил строку в файл PHP.INI.
Я пытался с HTTP и HTTP, но он по-прежнему показывает ноль. Я обновил адрес хоста, добавив URL-адрес вызова API, как показано на панели управления Azure. И не так много информации о людях, получающих эту ошибку.

<?php

// NOTE: Be sure to uncomment the following line in your php.ini file.
// ;extension=php_openssl.dll

// **********************************************
// *** Update or verify the following values. ***
// **********************************************

// Replace the subscriptionKey string value with your valid subscription key.
$key = 'KEY_REMOVED';

$host = "https://southeastasia.api.cognitive.microsoft.com/sts/v1.0/issuetoken";
$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 ($host, $path, $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;
?>

0

Решение

Как я знаю, ваш код скопирован из официального документа Quickstart: Translate text with the Translator Text REST API (PHP).

По разделу Base URLs ссылки Translator Text API v3.0, $host значение должно быть одним из списка ниже.

введите описание изображения здесь

Так что вы можете использовать $host = "https://api.cognitive.microsofttranslator.com"; в вашем коде без каких-либо изменений. Это первая проблема.

Во-вторых, Authentication заголовок зависит от вашего типа API вашей подписки Cognitive Services.

  1. Если ваш тип API Translator Text как показано на рисунке ниже, вы не будете менять $headers код в функции Translate исходного кода, значение которого зависит от вашего местоположения, например, southeastasia,

введите описание изображения здесь

  1. Если ваш тип API All Cognitive Services как показано на рисунке ниже, вам нужно добавить заголовок Ocp-Apim-Subscription-Region в $headers код.

введите описание изображения здесь

$headers = "Content-type: application/json\r\n" .
"Content-length: " . strlen($content) . "\r\n" .
"Ocp-Apim-Subscription-Key: $key\r\n" .
"Ocp-Apim-Subscription-Region: southeastasia\r\n" .
"X-ClientTraceId: " . com_create_guid() . "\r\n";

Заметка: есть проблема в документе как ниже.
введите описание изображения здесь

Тогда в моей среде версия PHP 7.2.12и я бегу php -f test.php который работает нормально и возвращает ответ json для двух разных случаев выше, как показано ниже.

введите описание изображения здесь

[
{
"detectedLanguage": {
"language": "en",
"score": 1
},
"translations": [
{
"text": "Hallo Welt!",
"to": "de"},
{
"text": "Salve, mondo!",
"to": "it"}
]
}
]
0

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]