php 转换API JSON文件中的数据

cwxwcias  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(56)

我使用一个API soccer,它提供了一个JSON数据文件,但默认的英语语言是这样的:

https://apiv3.apifootball.com/?action=get_countries&APIkey=xxxxxxxxxxxxxx

字符串
结果:

enter [
{ 
"country_id": "44",
"country_name": "England",
"country_logo": "https://apiv3.apifootball.com/badges/logo_country/44_england.png"
},
{
"country_id": "6",
"country_name": "Spain",
"country_logo": "https://apiv3.apifootball.com/badges/logo_country/6_spain.png"
},
{
"country_id": "3",
"country_name": "France",
"country_logo": "https://apiv3.apifootball.com/badges/logo_country/3_france.png"
},
{
"country_id": "4",
"country_name": "Germany",
"country_logo": "https://apiv3.apifootball.com/badges/logo_country/4_germany.png"
},
{
"country_id": "5",
"country_name": "Italy",
"country_logo": "https://apiv3.apifootball.com/badges/logo_country/5_italy.png"
},
....
]


我有一个多语言网站的问题,我想要的是一种在真实的时间背景下翻译成法语的方法:

[
 {
"country_id": "44",
"country_name": "Angleterre",
"country_logo": "https://apiv3.apifootball.com/badges/logo_country/44_england.png"
 },
.....


我花了几天的时间,但我没有成功地找到一个免费的PHP工具或方法,使JSON数据格式的翻译?

4jb9z9bj

4jb9z9bj1#

1.解析API返回的JSON结果。
1.使用循环为每个要翻译的元素依次调用翻译API(例如Google Translate APIMicrosoft Translator API)。
1.收集翻译结果以便进一步处理或显示。
举例来说:
您可以参考以下文档来使用Google Cloud Translation API:

require 'vendor/autoload.php';

use Google\Cloud\Translate\V2\TranslateClient;

function translateText($text, $targetLanguage, $apiKey) {
    $translate = new TranslateClient(['key' => $apiKey]);
    $result = $translate->translate($text, ['target' => $targetLanguage]);
    return $result['text'];
}

$jsonString = '[
    {
        "country_id": "44",
        "country_name": "England",
        "country_logo": "https://apiv3.apifootball.com/badges/logo_country/44_england.png"
    },
    ......
]';

$data = json_decode($jsonString, true);

$apiKey = 'YOUR_GOOGLE_CLOUD_API_KEY';  // Replace with your API key.

foreach ($data as $key => $value) {
    $data[$key]['country_name'] = translateText($value['country_name'], 'fr', $apiKey);
}

$newJsonString = json_encode($data, JSON_UNESCAPED_SLASHES);

字符串

相关问题