divineomega/php-countries

🌍 PHP Countries 是一个库,提供了优雅的语法来处理国家数据。

v2.3.0 2021-07-28 08:40 UTC

This package is auto-updated.

Last update: 2024-08-28 15:01:22 UTC


README

Build Status Coverage Status StyleCI Packagist

PHP Countries 是一个库,提供了优雅的语法来处理国家数据。

安装

您可以通过 Composer 安装 PHP Countries,如下所示。

composer require divineomega/php-countries

用法

要使用 PHP Countries,您必须创建一个新的 Countries 对象。

use DivineOmega\Countries\Countries;

$countries = new Countries;

然后您可以通过调用此对象的各种方法来获取国家数据。

获取所有国家

您可以通过以下方式轻松获取所有国家的数组并遍历它们。

foreach($countries->all() as $country) {
    var_dump($country->name.' - '.$country->officialName);
}

按名称获取国家

可以从国家的官方名称或通用名称获取国家详细信息。

var_dump($countries->getByName('United Kingdom'));

/* 
object(DivineOmega\Countries\Country)#146 (17) {
  ["name"]=>
  string(14) "United Kingdom"
  ["officialName"]=>
  string(52) "United Kingdom of Great Britain and Northern Ireland"
  ["topLevelDomains"]=>
  array(1) {
    [0]=>
    string(3) ".uk"
  }
  ["isoCodeAlpha2"]=>
  string(2) "GB"
  ["isoCodeAlpha3"]=>
  string(3) "GBR"
  ["isoCodeNumeric"]=>
  string(3) "826"
  ["languages"]=>
  array(1) {
    [0]=>
    string(7) "English"
  }
  ["languageCodes"]=>
  array(1) {
    [0]=>
    string(3) "eng"
  }
  ["currencyCodes"]=>
  array(1) {
    [0]=>
    string(3) "GBP"
  }
  ["callingCodes"]=>
  array(1) {
    [0]=>
    string(2) "44"
  }
  ["capital"]=>
  string(6) "London"
  ["capitals"]=>
  array(1) {
    [0]=>
    string(6) "London"
  }
  ["region"]=>
  string(6) "Europe"
  ["subregion"]=>
  string(15) "Northern Europe"
  ["latitude"]=>
  int(54)
  ["longitude"]=>
  int(-2)
  ["areaInKilometres"]=>
  int(242900)
  ["nationality"]=>
    string(7) "British"
}
*/

按 ISO 3166-1 编码获取国家

您可以通过 ISO 3166-1 编码获取国家的数据。接受 2 位、3 位和数字变体。

var_dump($countries->getByIsoCode('USA'));

/*
object(DivineOmega\Countries\Country)#4693 (16) {
  ["name"]=>
  string(13) "United States"
  ["officialName"]=>
  string(24) "United States of America"
  // etc...
}
*/

按使用的语言获取国家

提供一种语言,将返回一个包含在该语言中使用的所有国家的数组。您可以提供语言名称或代码。

var_dump($countries->getByLanguage('German'));

/*
array(5) {
  [0]=>
  object(DivineOmega\Countries\Country)#4913 (16) {
    ["name"]=>
    string(7) "Belgium"
    ["officialName"]=>
    // etc...
  }
  [1]=>
  object(DivineOmega\Countries\Country)#4883 (16) {
    ["name"]=>
    string(7) "Germany"
    ["officialName"]=>
    string(27) "Federal Republic of Germany"
    // etc...
  }
  [2]=>
  object(DivineOmega\Countries\Country)#4826 (16) {
    ["name"]=>
    string(13) "Liechtenstein"
    ["officialName"]=>
    string(29) "Principality of Liechtenstein"
    // etc...
  }
  [3]=>
  object(DivineOmega\Countries\Country)#4808 (16) {
    ["name"]=>
    string(10) "Luxembourg"
    ["officialName"]=>
    string(25) "Grand Duchy of Luxembourg"
    // etc...
  }
  [4]=>
  object(DivineOmega\Countries\Country)#4871 (16) {
    ["name"]=>
    string(7) "Namibia"
    ["officialName"]=>
    string(19) "Republic of Namibia"
    // etc...
  }
}
*/