PHP code example of universal-packages / country-service

1. Go to this page and download the library: Download universal-packages/country-service library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

universal-packages / country-service example snippets


use UniversalPackages\CountryService\CountryService;
use UniversalPackages\CountryService\DataLocale;

$service = new CountryService(DataLocale::EN_US);

// 国家列表
$countries = $service->getCountries();

// 某国省份
$provinces = $service->getProvinces('CN');

// 按国家名查询(大小写不敏感,自动 trim)
$country = $service->getCountryByName('China');      // Country(code: CN, name: China, ...)
$country = $service->getCountryByName('  china  ');  // 同样可命中
$country = $service->getCountryByName('NoCountry');  // null

// 解析:国家代码 → 国家名 + 省份列表
$result = $service->resolve('CN');  // China, 31 provinces

// 解析:国家-省份代码 → 国家名 + 省份名
$result = $service->resolve('CN-GD');  // China / Guangdong (GD)

// 省份不存在时的降级处理
$result = $service->resolve('CN-XX');                            // null(默认行为)
$result = $service->resolve('CN-XX', allowInvalidProvince: true); // CountryProvinceResolveResult(country: China, countryCode: CN, province: XX, provinceCode: XX)