PHP 使用浏览器语言头和 IP 来指定国际化多语言网站

前提:使用 wordpress ,未安装多语言插件,使用主题自己开发,使用 Poedit 来制作多语言,对应 zh_CN 这种。

第一:首先判断是否存在 GET 变量,然后 COOKIE 存储。

第二:使用浏览器头部标识来判断,这里找了一个国外作者写的一个函数来更好的获取语言标识,该函数返回两个字符,比如 zh 或者 en, 当然你也可以在结合$http_accept_language判断是否为 zh 中的 cn 或者 tw

function prefered_language($http_accept_language){

    $langs = array();
    preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER);
    foreach($matches as $match) {

        list($a, $b) = explode('-', $match[1]) + array('', '');
        $value = isset($match[2]) ? (float) $match[2] : 1.0;
        $langs[$a] = $value - 0.1;
    }
    if($langs) {
        arsort($langs);
        return key($langs); // We don't need the whole array of choices since we have a match
    }
}

第三使用 IP 来判断,因为有些搜索引擎不携带 $_SERVER['HTTP_ACCEPT_LANGUAGE'] 标识:

function ip_language($locale) {
    //自定义获取 ip 函数
    $ip = get_ip();
    $request = 'https://extreme-ip-lookup.com/json/'.$ip;
    $response = json_decode(curl_get($request),true);
    //请求成功
    if($response['status'] == 'success' && $response['countryCode']) {
        //国家代码
        $countryCode = $response['countryCode'];
        //洲代码
        $continent = $response['continent'];
        if($countryCode == 'TW' || $countryCode == 'HK' || $countryCode == 'SG') {
            setcookie('language', 'zh_TW');
            return 'zh_TW';
        }

        if($countryCode == 'CN') {
            setcookie('language', 'zh_CN');
            return 'zh_CN';
        }

        //北美
        if($continent == 'North America') {
            setcookie('language', 'en_US');
            return 'en_US';
        }
        

    } else {
        //返回默认语言
        return $locale;
    }
}

因为 wordpress 的 Poedit 采用 zh_CN 这种,所以开发时记得比对。

要用到浏览器规范语言头列表,和获取国家信息的全球国家标识规范列表,这里找到了两个网站使用比对处理:

Web browser language identification codes, 浏览器语言信息大全:

https://www.metamodpro.com/browser-language-codes

iso 规范全球国家名称以及简码;

https://www.iso.org/obp/ui/#search/code/

猜你喜欢

转载自blog.csdn.net/myarche/article/details/89413926