Get country list using curl

What is the best way to get a up-to-date countries list and load it to your web server’s DB?

Well, there are several ways to achieve this goal, and i will elaborate on the most effective and most comfortable way, development POV, of course : Using an existing API service from geonames.org.

First, you should register as a free API user with geonames on : http://www.geonames.org/login.

After that, the only thing you should do is download the attached lib on this post and you can start downloading the most up-to-date countries list available.

But before you start, i would like to walk you through the attached code, so you can understand the API better.

As many do, you can download PHP library from geonames (located here), but these sources are heavier and too big for my taste. I want my scripts to do one thing and one thing only, what they are meant to do!

So, you have the user name from geonames and downloaded the source code. Now we will upload the sources to your server directory (Domain or sub-domain) and we should configure the script.

The script support save to database or simple return of the output as a multi dimensional array.

The source code includes 3 files :

  1. db.sql – The table creation. run the script once under the database you want to support the countries list DB.
  2. OME_Curl.php – This is the curl class. I will not talk about it right now, just let me say this is a black box that can launch POST / GET request to remote forms / API’s.
  3. CountryList.php – This is the script that will handle the countries list as an array came from the geonames.org API.

 

I will create a full tutorial on working with this script, but for the time being, there are only few steps to make it work for your satisfaction.

First, Create the country table in your desired DB, create a new one or just add the table to an existing one.

After creating the table, go to the “CountryList.php” file and edit its configuration. You will find several constants you can configure in order to make this script work as you want :

  1. IS_SAVE_TO_DB – If true, the output from the API call will be saved to the country table in the DB. If false, in this                                        script it will dump the full array to the screen (Feel free to use the output as you see fit).
  2. HOST – The database host. Most of the time it will be “localhost” unless you use remote db.
  3. DB_NAME – The database name in the DB.
  4. DB_USER – The database user name credentials.
  5. DB_PASSWORD – The database password credentials.
  6. API_USER_NAME – The geonames user name you created earlier.

 

This is it, the script is ready to go .

I hope you will find this helpful.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*