PHP code example of happyphper / country

1. Go to this page and download the library: Download happyphper/country 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/ */

    

happyphper / country example snippets


use HappyPhper\Country\CountryCollection;

$collection = new CountryCollection();
$countries = $collection->getAll();

use HappyPhper\Country\CountryCollection;

$collection = new CountryCollection();

// 通过 ISO 3166-1 alpha-2 代码获取
$country = $collection->getByAlpha2('CN');

// 通过 ISO 3166-1 alpha-3 代码获取
$country = $collection->getByAlpha3('CHN');

// 通过 ISO 3166-1 numeric 代码获取
$country = $collection->getByNumeric('156');

$country = $collection->getByAlpha2('CN');

echo $country->getName();        // 输出: China
echo $country->getAlpha2();      // 输出: CN
echo $country->getAlpha3();      // 输出: CHN
echo $country->getNumeric();     // 输出: 156
echo $country->getFlagUrl();     // 输出: https://flagcdn.com/w320/cn.png

$country = $collection->getByAlpha2('CN');
echo $country->getFlagUrl();     // 输出: https://flagcdn.com/w320/cn.png

// 支持的宽度:20, 40, 80, 160, 320, 640, 1280, 2560
echo $country->getFlagUrlByWidth(640);  // 输出: https://flagcdn.com/w640/cn.png

// 支持的高度:20, 24, 40, 60, 80, 120, 240
echo $country->getFlagUrlByHeight(240);  // 输出: https://flagcdn.com/h240/cn.png

// 支持任意宽度和高度
echo $country->getFlagUrlByDimensions(16, 12);  // 输出: https://flagcdn.com/16x12/cn.png

// 支持的格式:png, webp, svg, jpg
echo $country->getFlagUrlByWidth(320, Country::FORMAT_WEBP);  // 输出: https://flagcdn.com/w320/cn.webp
echo $country->getFlagUrlByWidth(320, Country::FORMAT_SVG);   // 输出: https://flagcdn.com/w320/cn.svg
echo $country->getFlagUrlByWidth(320, Country::FORMAT_JPEG);  // 输出: https://flagcdn.com/w320/cn.jpg

echo $country->getSvgFlagUrl();  // 输出: https://flagcdn.com/cn.svg

use HappyPhper\Country\CountryCollection;

// 创建中文集合
$collection = new CountryCollection('zh-CN');
$china = $collection->getByAlpha2('CN');
echo $china->getLocalizedName(); // 输出: 中国

// 切换为繁体中文
$collection->setLocale('zh-TW');
echo $china->getLocalizedName(); // 输出: 中國

// 切换为英文
$collection->setLocale('en');
echo $china->getLocalizedName(); // 输出: China