gpt4 book ai didi

php - 使用 PHP 解码 Microsoft 翻译器 API 的 JSON 输出

转载 作者:可可西里 更新时间:2023-10-31 22:15:15 26 4
gpt4 key购买 nike

这个问题似乎特定于 microsofttranslator.com 所以请...任何答案,如果您可以针对它进行测试...

使用以下网址进行翻译:http://api.microsofttranslator.com/V2/Ajax.svc/TranslateArray .. 我通过 cURL 发送了一些奇妙的论点,并得到了以下结果:

 [
{
"From":"en",
"OriginalTextSentenceLengths":[13],
"TranslatedText":"我是最好的",
"TranslatedTextSentenceLengths":[5]
},
{
"From":"en",
"OriginalTextSentenceLengths":[16],
"TranslatedText":"你是最好的",
"TranslatedTextSentenceLengths":[5]
}
]

当我在 cURL 的输出上使用 json_decode($output, true); 时,json_decode 给出了一个错误,指出返回的 JSON 中的语法不合适:

 json_last_error() == JSON_ERROR_SYNTAX

与 JSON 一起返回的 header :

Response Headers

 Cache-Control:no-cache
Content-Length:244
Content-Type:application/x-javascript; charset=utf-8
Date:Sat, 06 Aug 2011 13:35:08 GMT
Expires:-1
Pragma:no-cache
X-MS-Trans-Info:s=63644

Raw content:

 [{"From":"en","OriginalTextSentenceLengths":[13],"TranslatedText":"我是最好的","TranslatedTextSentenceLengths":[5]},{"From":"en","OriginalTextSentenceLengths":[16],"TranslatedText":"你是最好的","TranslatedTextSentenceLengths":[5]}]

cURL code:

    $texts = array("i am the best" => 0, "you are the best" => 0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = array(
'appId' => $bing_appId,
'from' => 'en',
'to' => 'zh-CHS',
'texts' => json_encode(array_keys($texts))
);
curl_setopt($ch, CURLOPT_URL, $bingArrayUrl . '?' . http_build_query($data));
$output = curl_exec($ch);

最佳答案

API 返回错误的字节顺序标记 (BOM)。
字符串数据本身是 UTF-8,但前缀为 U+FEFF,这是一个 UTF-16 BOM。只需去掉前两个字节和 json_decode

...
$output = curl_exec($ch);
// Insert some sanity checks here... then,
$output = substr($output, 3);
...
$decoded = json_decode($output, true);

这是我的全部测试代码。

$texts = array("i am the best" => 0, "you are the best" => 0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = array(
'appId' => $bing_appId,
'from' => 'en',
'to' => 'zh-CHS',
'texts' => json_encode(array_keys($texts))
);
curl_setopt($ch, CURLOPT_URL, $bingArrayUrl . '?' . http_build_query($data));
$output = curl_exec($ch);
$output = substr($output, 3);
print_r(json_decode($output, true));

这给了我

Array
(
[0] => Array
(
[From] => en
[OriginalTextSentenceLengths] => Array
(
[0] => 13
)

[TranslatedText] => 我是最好的
[TranslatedTextSentenceLengths] => Array
(
[0] => 5
)

)

[1] => Array
(
[From] => en
[OriginalTextSentenceLengths] => Array
(
[0] => 16
)

[TranslatedText] => 你是最好的
[TranslatedTextSentenceLengths] => Array
(
[0] => 5
)

)

)

Wikipedia entry on BOM

关于php - 使用 PHP 解码 Microsoft 翻译器 API 的 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6967190/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com