Return to Snippet

Revision: 62212
at February 8, 2013 00:10 by Hexahow


Initial Code
<?php
////////////////////////////////////////////////////////////////////////////////////////////////
//The following codes populate the country list into dropdown box based on  browser's languages.
//The country information is getting from geolocation.com, 
//free license with attribution: The geolocation data is provided by http://www.geolocation.com

//Get the languages
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
	echo '<p>Browser Languages: ' . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . '</p>';
	echo '<p style="margin:0px; padding:0px;">Country List <span style="font-size:9pt; display:block;">The geolocation data is provided by <a href="http://www.geolocation.com">http://www.geolocation.com</a></span></p>';
	
	////////////////////////////
	//Get the browser languages
	if(preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_matches)){
		$langs = array_combine($lang_matches[1], $lang_matches[4]);
		foreach ($langs as $lang => $val)
		  if ($val === '') $langs[$lang] = 1;
		  
		arsort($langs, SORT_NUMERIC);
	}
	
	//Default to english
	$language = 'en-us';
	foreach ($langs as $lang => $val){
		$language = $lang;
		break;
	}
	
	//////////////////////
	//Load the Country File
	//Notes: 
	//Download the CSV file from http://www.geolocation.com
	//Rename the CSV to country-en-us.csv (for english version),
	//country-zh-cn.csv (for chinese simplified version),
	//country-zh-tw.csv (for chinese traditional version)
	//and save in the same folder as the php code resided.
	echo '<select>';
	$countries = file_get_contents("country-$language.csv");
	if (preg_match_all('/"(.*?)","(.*?)","(.*?)","(.*?)"/', $countries, $matches)){
		for($nIdx=1; $nIdx < count($matches[1]); $nIdx++){
			$alpha2_code = $matches[1][$nIdx];
			$country_name = $matches[4][$nIdx];
			//echo $alpha2_code . ',' . $country_name . '<br/>';
			echo '<option value=' . $alpha2_code . '">' . $country_name . '</option>';
		}
	}
	echo '</select>';

}
else
	echo 'Unable to locate browser languages';
?>

Initial URL
http://www.geolocation.com

Initial Description
The following codes populate the country list into dropdown box based on browser's languages. The country information is getting from geolocation.com

Initial Title
Country list based on browser's language

Initial Tags
list, ip

Initial Language
PHP