gilbertchiao/taiwan-county-city

A PHP library for listing cities and counties in Taiwan, with their English names and other data.

v1.0.0 2025-07-19 04:05 UTC

This package is auto-updated.

Last update: 2025-07-19 04:09:59 UTC


README

此專案提供一個簡單的方式,在 PHP 應用程式中取用台灣的縣市基本資料。資料來源為交通部運輸資料流通服務平臺 (TDX),並已預先處理成方便 PHP 直接使用的格式,無需每次都從資料庫查詢或解析 JSON 檔案。

安裝

您可以使用 Composer 來安裝此套件:

composer require gilbertchiao/taiwan-county-city

如何使用

根據您的 PHP 版本與偏好,選擇以下其中一種方式使用。

方法一:使用 Cities Class (通用)

這個方法適用於所有 PHP 版本,提供簡單的靜態方法來獲取資料。

範例:

require_once __DIR__ . '/vendor/autoload.php';

use TaiwanData\Cities;

// 取得所有縣市資料
$allCities = Cities::getAllCities();
print_r($allCities);

// 根據 CountyID 取得新竹市的資料 ('O')
$hsinchuCity = Cities::getCityById('O');
if ($hsinchuCity) {
    echo "新竹市的中文名稱:" . $hsinchuCity['CountyName'] . "\n"; // 輸出: 新竹市
    echo "新竹市的英文名稱:" . $hsinchuCity['County'] . "\n";   // 輸出: Hsinchu
}

// 取得所有縣市的中文名稱列表
$countyNames = Cities::getCountyNames();
print_r($countyNames);

// 根據中文名稱取得臺北市資料
$taipeiCity = Cities::getCityByName('臺北市');
if ($taipeiCity) {
    echo "臺北市的 CountyCode:" . $taipeiCity['CountyCode'] . "\n"; // 輸出: 63000
}

方法二:使用 CityEnum (PHP 8.1+)

如果您使用 PHP 8.1 或更新版本,建議使用 Enum 以獲得更佳的型別安全與可讀性。

範例:

require_once __DIR__ . '/vendor/autoload.php';

use TaiwanData\CityEnum;

// 直接使用 Enum Case
$taipei = CityEnum::TAIPEI;

// 獲取詳細資料
$taipeiDetails = $taipei->getDetails();
echo "臺北市的 CountyCode: " . $taipeiDetails['CountyCode'] . "\n"; // 輸出: 63000

// 獲取中文名稱
echo "中文名稱: " . $taipei->getCountyName() . "\n"; // 輸出: 臺北市

// 從 CountyID 動態獲取 Enum Case
$hsinchu = CityEnum::fromCountyId('O');
if ($hsinchu) {
    echo "新竹市的英文名稱: " . $hsinchu->getCountyEnglishName() . "\n"; // 輸出: Hsinchu
}

// 獲取所有縣市的中文名稱
$allNames = CityEnum::getAllCountyNames();
print_r($allNames);

資料來源

所有資料皆來自交通部運輸資料流通服務平臺 (TDX) 的「全臺縣市代碼資料(City) v2」與「全臺縣市代碼資料(County) v2」。

  • 原始資料位於 data/basic_city.jsondata/basic_county.json
  • 合併後的完整資料為 data/city_county.json

由於此資料不常異動,專案將其轉換為 PHP Class 或 Enum,以便在程式中更有效率地取用。