Friday, September 2, 2011

Select Country Drop Down based on country location with flag with PHP

Selecting country name from country drop down based on the visitors country location will increase visitors user friendliness for your web forms, Let us create How to create Auto Select Country Name based on visitors location based on Country Geo location and  IP Address. When Loading a page detect country name and locate a country flag based on country location.

Create a Free Account for IP to Location API from  to get a API Key for IP to Location. and get the Country Flag from ip2Location database.
using the URL:{ COUNTRY SHORT CODE} .gif

and Process the code as per the following:


// CountryList as Array 
// Country ShortCode as Key Country Name as Value;
$world_countires=array('AF'=>'Afghanistan (افغانستان)');
// Note: Download Full Country Array from Download Link from end of this Article

function xml2array($xml) {
  foreach($xml->attributes() as $name => $value) $t[$name]=trim($value);
  foreach($xml->children() as $name => $xmlchild) $t[$name]=xml2array($xmlchild);

$xml = simplexml_load_file(''.$_SERVER['REMOTE_ADDR']);


// Check if Local

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Auto Select Country Dropdown based on Location : Demo</title>
<style type="text/css">
body,td,th {
	font-family: Verdana, Geneva, sans-serif;
	font-size: 11px;
	color: #333;
body {
	margin-left: 20px;
	margin-top: 20px;


<h2>PHP Auto Populate Country Name in Country Drop Down List with Flag</h2>
<table border="0" cellspacing="0" cellpadding="5">
<script type="text/javascript">
function setFlag(country_code)
	document.getElementById('flag').src=""+ country_code +".gif";

<select name="country_name" onchange="setFlag(this.value)" style="font-family:Verdana, Geneva, sans-serif; width:200px; font-size:15px; border:1px solid #999;">
<option value="">Select Country</option>
foreach($world_countires as $short_code=>$country_name)
	echo "<option value=\"$short_code\" selected=\"selected\">$country_name</option>";
	echo "<option value=\"$short_code\">$country_name</option>";
    <td><img id="flag" src="<?=$country_code?>.gif" width="30" height="20" /></td>


Download This Script     Live Demo     Download Script

No comments:

Post a Comment