logo

XML/JSON API Code

We were asked a few times the code of our IP Location APIs so here they are. If you see ways to improve them (especially for speed) please let us know in the forum.

Both IP database and timezone database must be installed!

ip_query.php
<?php
 
//connect to db
$con = mysql_connect('localhost', 'XXXXXX', 'XXXXXX') or die(mysql_error());
 
if (!$con) {
  die('Could not connect: ' . mysql_error());
}
 
mysql_select_db('IPDB', $con);
 
//Get the parameters
if ($_GET["ip"]){
  $ip = mysql_real_escape_string(trim($_GET["ip"]), $con);
} else {
  $ip = getenv('REMOTE_ADDR');
}
if ($_GET["output"]) $output = $_GET["output"];
if ($_GET["callback"]) $callback = $_GET["callback"];
if (isset($_GET["timezone"])) {
  $newTimezone = true;
  if ($_GET["timezone"] == 'true') {
    $showNewTimezone = true;
  }
} else {
  $newTimezone = false;
}
 
//Run the IP location query
$ipQuery = mysql_query("SELECT * FROM `ip_group_city` where `ip_start` <= INET_ATON('$ip') order by ip_start desc limit 1;", $con);
$ipData = mysql_fetch_array($ipQuery);
$nbResults = (bool)mysql_num_rows($ipQuery);
$geolocationArr['Ip'] = $ip;
if ($nbResults) {
  $geolocationArr['Status'] = 'OK';
} else {
  $geolocationArr['Status'] = 'IP NOT FOUND IN DATABASE, SORRY!';
}                     
$geolocationArr['CountryCode'] = $ipData['country_code'];
$geolocationArr['CountryName'] = utf8_encode($ipData['country_name']);
$geolocationArr['RegionCode'] = $ipData['region_code'];
$geolocationArr['RegionName'] = utf8_encode($ipData['region_name']);
$geolocationArr['City'] = utf8_encode($ipData['city']);
$geolocationArr['ZipPostalCode'] = $ipData['zipcode'];
$geolocationArr['Latitude'] = $ipData['latitude'];
$geolocationArr['Longitude'] = $ipData['longitude'];
 
if (!$newTimezone) {
  $geolocationArr['Timezone'] = $ipData['timezone'];
  $geolocationArr['Gmtoffset'] = $ipData['gmtOffset'];
  $geolocationArr['Dstoffset'] = $ipData['dstOffset'];
} else {
  if ($showNewTimezone) {
    if ($nbResults) {
      mysql_select_db('troquez', $con);
      $tzQuery = mysql_query("SELECT tzd.gmtoff as gmtoff, tzd.isdst as isdst, tz.name as name FROM `timezones_data` tzd JOIN `timezones` tz ON tz.id = tzd.timezone WHERE tzd.timezone = (SELECT `timezone` FROM `fips_regions` WHERE `country_code` = '" . mysql_real_escape_string($ipData['country_code'], $con) . "' AND `code` = '" . mysql_real_escape_string($ipData['region_code'], $con) . "' ) AND tzd.start < UNIX_TIMESTAMP( now( ) ) ORDER BY tzd.start DESC LIMIT 1", $con);
      $tzData = mysql_fetch_array($tzQuery);
    }
    $geolocationArr['TimezoneName'] = $tzData['name'];
    $geolocationArr['Gmtoffset'] = $tzData['gmtoff'];
    $geolocationArr['Isdst'] = $tzData['isdst'];
  }
}
 
//Show the results
switch($output){
 
  case 'raw':
    header('Content-Type: text/html; charset=UTF-8');
    foreach($geolocationArr as $field => $value) {
      $outputArr[] = $value;   
    }
    echo implode(",", $outputArr);
  break;
 
  case 'json':
    header('Content-Type: text/json; charset=UTF-8');
    if ($callback){
      echo "$callback(\n";
      echo "  {\n";
      foreach($geolocationArr as $field => $value) {
        $outputArr[] = "    \"$field\" : \"$value\"";
      }
      echo implode(",\n", $outputArr) . "\n";
      echo "  }\n";                               
      echo ")";
    } else {
      echo "{\n";
      foreach($geolocationArr as $field => $value) {
        $outputArr[] = "  \"$field\" : \"$value\"";
      }
      echo implode(",\n", $outputArr) . "\n";
      echo "}\n";
    }
  break;
 
  default:
    header('Content-type: text/xml');
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    echo "<Response>\n";
    foreach($geolocationArr as $field => $value) {
      $outputArr[] = "  <{$field}>{$value}</{$field}>";
    }
    echo implode("\n", $outputArr) . "\n";
    echo "</Response>\n";
  break;
}
?>
ip_query2.php
<?php
 
//connect to db
$con = mysql_connect('localhost', 'XXXXXX', 'XXXXXX') or die(mysql_error());
 
if (!$con) {
  die('Could not connect: ' . mysql_error());
}
 
//Get the parameters
if ($_GET["ip"]){
  $ips = $_GET["ip"];
} else {
  $ips = getenv('REMOTE_ADDR');
}
if ($_GET["output"]) $output = $_GET["output"];
if ($_GET["callback"]) $callback = $_GET["callback"];
if (isset($_GET["timezone"])) {
  $newTimezone = true;
  if ($_GET["timezone"] == 'true') {
    $showNewTimezone = true;
  }
} else {
  $newTimezone = false;
}
 
//Explode the IP list
$ipsArr = explode(",",$ips);
 
$counter = 0;
if ((sizeof($ipsArr) <= 25) && (sizeof($ipsArr) > 0) ){
  foreach($ipsArr as $ip) {
 
    //MySQL safe
    $ip = mysql_real_escape_string(trim($ip), $con);
 
    //Check for domain
    if(preg_match('/[a-zA-Z]/',$ip)){
      $domain = $ip;
      $ip = gethostbyname($domain);
      sleep(1);
    }  
 
    mysql_select_db('IPDB', $con);
    $ipQuery = mysql_query("SELECT * FROM `ip_group_city` where `ip_start` <= INET_ATON('$ip') order by ip_start desc limit 1;", $con);
    $ipData = mysql_fetch_array($ipQuery);
    $nbResults = (bool)mysql_num_rows($ipQuery);
    $geolocationsArr[$counter]['Ip'] = $ip;
    if ($nbResults) {
      $geolocationsArr[$counter]['Status'] = 'OK';
    } else {
      $geolocationsArr[$counter]['Status'] = 'IP NOT FOUND IN DATABASE, SORRY!';
    }                     
    $geolocationsArr[$counter]['CountryCode'] = $ipData['country_code'];
    $geolocationsArr[$counter]['CountryName'] = utf8_encode($ipData['country_name']);
    $geolocationsArr[$counter]['RegionCode'] = $ipData['region_code'];
    $geolocationsArr[$counter]['RegionName'] = utf8_encode($ipData['region_name']);
    $geolocationsArr[$counter]['City'] = utf8_encode($ipData['city']);
    $geolocationsArr[$counter]['ZipPostalCode'] = $ipData['zipcode'];
    $geolocationsArr[$counter]['Latitude'] = $ipData['latitude'];
    $geolocationsArr[$counter]['Longitude'] = $ipData['longitude'];
 
    if (!$newTimezone) {
      $geolocationsArr[$counter]['Timezone'] = $ipData['timezone'];
      $geolocationsArr[$counter]['Gmtoffset'] = $ipData['gmtOffset'];
      $geolocationsArr[$counter]['Dstoffset'] = $ipData['dstOffset'];
    } else {
      if ($showNewTimezone) {
        if ($nbResults) {
          mysql_select_db('TIMEZONEDB', $con);
          $tzQuery = mysql_query("SELECT tzd.gmtoff as gmtoff, tzd.isdst as isdst, tz.name as name FROM `timezones_data` tzd JOIN `timezones` tz ON tz.id = tzd.timezone WHERE tzd.timezone = (SELECT `timezone` FROM `fips_regions` WHERE `country_code` = '" . mysql_real_escape_string($ipData['country_code'], $con) . "' AND `code` = '" . mysql_real_escape_string($ipData['region_code'], $con) . "' ) AND tzd.start < UNIX_TIMESTAMP( now( ) ) ORDER BY tzd.start DESC LIMIT 1", $con);
          $tzData = mysql_fetch_array($tzQuery);
        }
        $geolocationsArr[$counter]['TimezoneName'] = $tzData['name'];
        $geolocationsArr[$counter]['Gmtoffset'] = $tzData['gmtoff'];
        $geolocationsArr[$counter]['Isdst'] = $tzData['isdst'];
      }
    }
    usleep(10000);
    $counter++;
  }
}
 
switch($output){
 
  case 'raw':
    header('Content-Type: text/html; charset=UTF-8');
    foreach($geolocationsArr as $geolocationArr) {
      $outputArr = array();
      foreach($geolocationArr as $field => $value) {
        $outputArr[] = $value;   
      }
      echo implode(",", $outputArr) . "\n";
    }
  break;
 
  case 'json':
    header('Content-Type: text/json; charset=UTF-8');
    if ($callback){
      echo "$callback(\n";
      echo "  {\n";
      echo "    \"Locations\": [\n";
      foreach($geolocationsArr as $key => $geolocationArr) {
        $outputArr = array();
        $outputArr[] = "        \"Id\" : \"$key\"";
        foreach($geolocationArr as $field => $value) {
          $outputArr[] = "        \"$field\" : \"$value\"";
        }
        echo "      {\n";
        echo implode(",\n", $outputArr) . "\n";
        //Add comma if not last location
        if ($key == (sizeof($geolocationsArr) - 1)) {
          echo "      }\n";
        } else {
          echo "      },\n";
        }
      }
      echo "    ]\n";
      echo "  }\n";
      echo ")";
    } else {
      echo "{\n";
      echo "  \"Locations\": [\n";
      foreach($geolocationsArr as $key => $geolocationArr) {
        $outputArr = array();
        $outputArr[] = "      \"Id\" : \"$key\"";
        foreach($geolocationArr as $field => $value) {
          $outputArr[] = "      \"$field\" : \"$value\"";
        }
        echo "    {\n";
        echo implode(",\n", $outputArr) . "\n";
        //Add comma if not last location
        if ($key == (sizeof($geolocationsArr) - 1)) {
          echo "    }\n";
        } else {
          echo "    },\n";
        }
      }
      echo "  ]\n";
      echo "}\n";
    }
  break;
 
  default:
    header('Content-type: text/xml');
    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    echo "<Locations>\n";
    foreach($geolocationsArr as $key => $geolocationArr) {
      $outputArr = array();
      echo "  <Location id=\"$key\">\n";
      foreach($geolocationArr as $field => $value) {
        $outputArr[] = "    <{$field}>{$value}</{$field}>";
      }
      echo implode("\n", $outputArr) . "\n";
      echo "  </Location>\n";
    }
    echo "</Locations>\n";
  break;
}
?>
Keeping in touch for updates

The best way to get updates and news is with our RSS feed or on Twitter.