Tag Archives: XML

Getting Geolocation details and then using them to extract 1 Groupon Deal

Recently I’ve been trying out for a variety of roles and on a recent one they sent me a questionnaire with two PHP challenges. The first one, given here, asks us to use a web service to get a users Lat and long based on their IP and then use this to query groupon for 1 deal in their location. The format of the query will be in the fom of a GET variable called ip={THE USERS IP} for example

www.example.com/challenge1.php?ip=12.14.25.223

The result should be an XML file. I’ve solved the bulk of it below, but I still have to figure out how to respond when you have no deals found.

<?php
if(isset($_GET['ip'])){

	$location = file_get_contents('http://freegeoip.net/json/'.$_GET['ip']);
	$ip_json=json_decode($location,true);
	$lat = $ip_json&#91;"latitude"&#93;;
	$long = $ip_json&#91;"longitude"&#93;;
	if(strlen($lat)>1 && strlen($long)>1){		

		$groupon_url='http://partner-api.groupon.com/deals.json?tsToken=insert_tracking_token_here&lat='.$lat.'&lng='.$long.'&limit=1&offset=0';

		$gr_string = file_get_contents($groupon_url);
		$gr_json=json_decode($gr_string,true);


		$title = $gr_json["deals"][0]["title"];
		$desc = strip_tags($gr_json["deals"][0]["pitchHtml"]);
		$disp_url = $gr_json["deals"][0]["dealUrl"];
		$clk_url = $gr_json["deals"][0]["options"][0]["buyUrl"];

		//-----THIS GENERATES THE XML-----------//

		header('Content-type: text/xml');
		header('Pragma: public');
		header('Cache-control: private');
		header('Expires: -1');
		echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
		echo '<xml>';
		echo '<results>';
		echo '<title>'.$title.'</title>';
		echo '<desc>'.$desc.'</desc>';
		echo '<display_url>'.$disp_url.'</display_url>';
		echo '<click_url>'.$clk_url.'</click_url>';
		echo '</results>';
		echo '</xml>';
	}
	else{
		echo "Could not resolve the ip into lat and long";
	}
}
else{
	header('Content-type: text/xml');
	header('Pragma: public');
	header('Cache-control: private');
	header('Expires: -1');
	echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
	echo '<xml>';
	echo '</xml>';
}