PHPackages                             farzai/geonames - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. farzai/geonames

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

farzai/geonames
===============

A PHP library for downloading and converting Geonames data.

2.1.0(1y ago)1853[2 PRs](https://github.com/farzai/geonames-php/pulls)MITPHPPHP ^8.1CI passing

Since Oct 22Pushed 1mo agoCompare

[ Source](https://github.com/farzai/geonames-php)[ Packagist](https://packagist.org/packages/farzai/geonames)[ Docs](https://github.com/farzai/geonames-php)[ GitHub Sponsors](https://github.com/parsilver)[ RSS](/packages/farzai-geonames/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (8)Versions (14)Used By (0)

Geoname data (PHP)
==================

[](#geoname-data-php)

[![Latest Version on Packagist](https://camo.githubusercontent.com/cbe9340efd5ec9bb90f3303c46cf6edc0e714cb7bda1cb3400a3a3a8e9294ef0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6661727a61692f67656f6e616d65732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/farzai/geonames-php)[![Tests](https://camo.githubusercontent.com/5e89f3a89d2a5b67b1e671d22f699091a1f0ba0d25299072c0784c83534d1c2b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6661727a61692f67656f6e616d65732d7068702f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/farzai/geonames-php/actions/workflows/run-tests.yml)[![codecov](https://camo.githubusercontent.com/dca385d9ef4e7b0a9927937e45917348599b6f24a5e709326a3e09cdb45b5686/68747470733a2f2f636f6465636f762e696f2f67682f6661727a61692f67656f6e616d65732d7068702f6272616e63682f6d61696e2f67726170682f62616467652e737667)](https://codecov.io/gh/farzai/geonames-php)[![Total Downloads](https://camo.githubusercontent.com/9062410dfcab92923d3a74062553b2c221746806d54d889a913071c98deac34d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6661727a61692f67656f6e616d65732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/farzai/geonames)A PHP library for downloading and converting Geonames data. This library provides easy access to both Postal Codes and Gazetteer data from Geonames.

Features
--------

[](#features)

- Download postal codes data for specific countries or all countries
- Download detailed geographical data (Gazetteer) including administrative divisions
- Convert data to JSON format with proper structure
- Import data directly to MongoDB with proper indexing
- Memory-efficient processing for large datasets
- Progress bars for all operations

How It Works
------------

[](#how-it-works)

### Admin Code Resolution

[](#admin-code-resolution)

When downloading gazetteer data, the library automatically downloads `admin1CodesASCII.txt` and `admin2Codes.txt` from GeoNames to resolve administrative division names (e.g., converting admin code "40" to "Bangkok").

### Memory-Efficient Processing

[](#memory-efficient-processing)

Data is processed using streaming to handle large datasets without exhausting memory. For MongoDB imports, records are inserted in batches of 1000 for optimal performance.

### Automatic Cleanup

[](#automatic-cleanup)

Temporary files (downloaded ZIP files, extracted data files, and admin code files) are automatically cleaned up after processing completes.

Installation
------------

[](#installation)

```
composer require farzai/geonames
```

Usage
-----

[](#usage)

### Postal Codes

[](#postal-codes)

Download postal codes for a specific country:

```
./bin/geonames geonames:download TH
```

Download postal codes for all countries:

```
./bin/geonames geonames:download all
```

Options:

- `--output (-o)`: Output directory (default: ./data)
- `--format (-f)`: Output format (default: json, options: json, mongodb)
- `--mongodb-uri`: MongoDB connection URI (default: mongodb://localhost:27017)
- `--mongodb-db`: MongoDB database name (default: geonames)
- `--mongodb-collection`: MongoDB collection name (default: postal\_codes)

The postal codes data includes:

- Country code
- Postal code
- Place name
- Administrative divisions (state/province, county/district, community)
- Latitude and longitude
- Accuracy level

### Gazetteer Data

[](#gazetteer-data)

Download geographical data for a specific country:

```
./bin/geonames geonames:gazetteer:download TH
```

Download geographical data for all countries:

```
./bin/geonames geonames:gazetteer:download all
```

Options:

- `--output (-o)`: Output directory (default: ./data)
- `--format (-f)`: Output format (default: json, options: json, mongodb)
- `--mongodb-uri`: MongoDB connection URI (default: mongodb://localhost:27017)
- `--mongodb-db`: MongoDB database name (default: geonames)
- `--mongodb-collection`: MongoDB collection name (default: gazetteer)

The Gazetteer data includes:

- Geoname ID
- Name (with ASCII and alternate names)
- Geographical coordinates
- Feature class and code
- Administrative divisions with names
- Population
- Elevation
- Digital elevation model (DEM)
- Timezone
- Modification date

Data Structure
--------------

[](#data-structure)

### Postal Codes Structure

[](#postal-codes-structure)

#### JSON Format

[](#json-format)

```
{
    "country_code": "TH",
    "postal_code": "10200",
    "place_name": "Bang Rak",
    "admin_name1": "Bangkok",
    "admin_code1": "10",
    "admin_name2": "",
    "admin_code2": "",
    "admin_name3": "",
    "admin_code3": "",
    "latitude": 13.7235,
    "longitude": 100.5147,
    "accuracy": 1
}
```

#### MongoDB Format

[](#mongodb-format)

In MongoDB, the postal codes data has the same structure as JSON but includes an additional `location` field for geospatial queries:

```
{
    "country_code": "TH",
    "postal_code": "10200",
    "place_name": "Bang Rak",
    "admin_name1": "Bangkok",
    "admin_code1": "10",
    "admin_name2": "",
    "admin_code2": "",
    "admin_name3": "",
    "admin_code3": "",
    "latitude": 13.7235,
    "longitude": 100.5147,
    "accuracy": 1,
    "location": {
        "type": "Point",
        "coordinates": [100.5147, 13.7235]
    }
}
```

The MongoDB collection is indexed for efficient queries:

- Compound index on `country_code` and `postal_code` (unique)
- Index on `country_code`
- Index on `postal_code`
- Geospatial index on `location`

### Gazetteer Structure

[](#gazetteer-structure)

#### JSON Format

[](#json-format-1)

```
{
    "geoname_id": 1609350,
    "name": "Bangkok",
    "ascii_name": "Bangkok",
    "alternate_names": ["Krung Thep", "กรุงเทพมหานคร"],
    "latitude": 13.75,
    "longitude": 100.51667,
    "feature_class": "P",
    "feature_code": "PPLC",
    "country_code": "TH",
    "cc2": [],
    "admin1_code": "40",
    "admin1_name": "Bangkok",
    "admin2_code": "",
    "admin2_name": "",
    "admin3_code": "",
    "admin4_code": "",
    "population": 5104476,
    "elevation": 2,
    "dem": 4,
    "timezone": "Asia/Bangkok",
    "modification_date": "2023-01-12"
}
```

#### MongoDB Format

[](#mongodb-format-1)

In MongoDB, the gazetteer data uses slightly different field names and includes a `location` field for geospatial queries:

```
{
    "geonameid": 1609350,
    "name": "Bangkok",
    "asciiname": "Bangkok",
    "alternatenames": ["Krung Thep", "กรุงเทพมหานคร"],
    "location": {
        "type": "Point",
        "coordinates": [100.51667, 13.75]
    },
    "feature_class": "P",
    "feature_code": "PPLC",
    "country_code": "TH",
    "cc2": [],
    "admin1_code": "40",
    "admin1_name": "Bangkok",
    "admin2_code": "",
    "admin2_name": "",
    "admin3_code": "",
    "admin4_code": "",
    "population": 5104476,
    "elevation": 2,
    "dem": 4,
    "timezone": "Asia/Bangkok",
    "modification_date": "2023-01-12"
}
```

The MongoDB collection is indexed for efficient queries:

- Geospatial index on `location`

MongoDB Usage Examples
----------------------

[](#mongodb-usage-examples)

### Finding locations near a point

[](#finding-locations-near-a-point)

```
$client = new MongoDB\Client('mongodb://localhost:27017');
$collection = $client->geonames->gazetteer;

// Find all places within 5km of Bangkok
$result = $collection->find([
    'location' => [
        '$near' => [
            '$geometry' => [
                'type' => 'Point',
                'coordinates' => [100.51667, 13.75] // [longitude, latitude]
            ],
            '$maxDistance' => 5000 // 5km in meters
        ]
    ]
]);

foreach ($result as $place) {
    echo $place['name'] . ' - ' . $place['feature_code'] . PHP_EOL;
}
```

### Finding postal codes by country

[](#finding-postal-codes-by-country)

```
$client = new MongoDB\Client('mongodb://localhost:27017');
$collection = $client->geonames->postal_codes;

// Find all postal codes in Bangkok, Thailand
$result = $collection->find([
    'country_code' => 'TH',
    'admin_name1' => 'Bangkok'
]);

foreach ($result as $postalCode) {
    echo $postalCode['postal_code'] . ' - ' . $postalCode['place_name'] . PHP_EOL;
}
```

Error Handling
--------------

[](#error-handling)

The library throws `Farzai\Geonames\Exceptions\GeonamesException` for all error conditions:

```
use Farzai\Geonames\Exceptions\GeonamesException;

try {
    // Download or convert operations
} catch (GeonamesException $e) {
    echo "Error: " . $e->getMessage();
}
```

Common error scenarios:

- **File operation failures**: Unable to read, write, or open files
- **ZIP extraction failures**: Corrupted or invalid ZIP archives
- **Data not found**: Missing expected data files in downloaded archives
- **Missing dependencies**: MongoDB extension not installed when using MongoDB format

License
-------

[](#license)

This package is open-sourced software licensed under the MIT license.

Credits
-------

[](#credits)

- Data provided by [GeoNames](https://www.geonames.org/) under a [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/)
- Developed by [Parsilver](https://github.com/parsilver)

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance70

Regular maintenance activity

Popularity13

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 69% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~143 days

Recently: every ~200 days

Total

7

Last Release

441d ago

Major Versions

1.0.3 → v2.x-dev2025-02-13

PHP version history (2 changes)1.0.0PHP &gt;=7.4

v2.x-devPHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/4928451?v=4)[parsilver](/maintainers/parsilver)[@parsilver](https://github.com/parsilver)

---

Top Contributors

[![parsilver](https://avatars.githubusercontent.com/u/4928451?v=4)](https://github.com/parsilver "parsilver (49 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (14 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (7 commits)")[![hrant1020](https://avatars.githubusercontent.com/u/28590762?v=4)](https://github.com/hrant1020 "hrant1020 (1 commits)")

---

Tags

countriescountry-codesdatageographygeonamesdatacountriesgeonames

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/farzai-geonames/health.svg)

```
[![Health](https://phpackages.com/badges/farzai-geonames/health.svg)](https://phpackages.com/packages/farzai-geonames)
```

###  Alternatives

[shlinkio/shlink

A self-hosted and PHP-based URL shortener application with CLI and REST interfaces

4.8k4.3k](/packages/shlinkio-shlink)[glhd/conveyor-belt

14797.0k](/packages/glhd-conveyor-belt)[flarum/core

Delightfully simple forum software.

211.3M1.9k](/packages/flarum-core)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[aternus/geonames-client

GeoNames API Client

39215.5k2](/packages/aternus-geonames-client)[eliashaeussler/typo3-solver

Extension for TYPO3 CMS to extend TYPO3's exception handling with AI generated solutions

292.1k](/packages/eliashaeussler-typo3-solver)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
