You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何读取本地JSON国家数据并按国家代码查询对应信息

实现方案

步骤1:存储JSON数据

把你拿到的国家JSON数据保存到项目目录下,命名为countries.json。

步骤2:编写查询功能代码

直接写可复用的函数,逻辑如下:

<?php
function getCountryInfo(string $countryCode): ?array
{
    // 国家JSON文件路径,可根据实际存放位置调整
    $jsonPath = __DIR__ . '/countries.json';
    if (!file_exists($jsonPath)) {
        return null;
    }
    // 解析JSON为数组格式
    $countryList = json_decode(file_get_contents($jsonPath), true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        return null;
    }
    // 以国家二字码为键重组数组,实现O(1)效率查询
    $countryIndex = array_column($countryList, null, 'code');
    // 统一转大写避免大小写不匹配问题
    $countryCode = strtoupper(trim($countryCode));
    if (!isset($countryIndex[$countryCode])) {
        return null;
    }
    // 仅返回需要的三个字段
    return [
        'name' => $countryIndex[$countryCode]['name'],
        'dialCode' => $countryIndex[$countryCode]['dialCode'],
        'emoji' => $countryIndex[$countryCode]['emoji']
    ];
}

调用示例

// 示例1:单独查询指定国家代码的信息
$aoInfo = getCountryInfo('AO');
print_r($aoInfo);
/* 输出结果:
Array
(
    [name] => Angola
    [dialCode] => +244
    [emoji] => 🇦🇴
)
*/

// 示例2:结合你原有的IP定位逻辑使用
$visitorCountry = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
$visitorInfo = getCountryInfo($visitorCountry);
if ($visitorInfo) {
    echo "您所在国家:{$visitorInfo['name']},国际区号:{$visitorInfo['dialCode']} {$visitorInfo['emoji']}";
}

提示:如果站点访问量较大,建议将解析后的国家索引数组存入缓存(比如APCu、Redis),避免每次请求都重复读取解析JSON文件,提升性能。

内容的提问来源于stack exchange,提问作者tramp Kolo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 05:45:03