Quick & dirty PHP geocoding script

Attention: open in a new window.  Print  E-mail

Here's a quick script to geocode entries in a database.  It's trivial, but handy. It currently uses a Joomla JConfig object to connect to the datababase

<?php
 
include ("index.php");
 
$conf = new JConfig();
 
$conn = mysql_connect("localhost",$conf->user,$conf->password);
 
mysql_select_db($conn);
 
$result = mysql_query("SELECT address,id from jos_gmaps_markers where address is not null and address != '(NULL)'");
 
while($row = mysql_fetch_assoc($result)){
    
   // Your Google Maps API key
   $key = "PUT_YOUR_KEY_HERE";
 
   // Desired address
   $address = "http://maps.google.com/maps/geo?q=".urlencode($row['address'])."&output=xml&key=$key";
 
   // Retrieve the URL contents
   $page = file_get_contents($address);
 
   try {
           // Parse the returned XML file
        $xml = new SimpleXMLElement($page);
   }catch(Exception $e){
   
   }
 
   list($longitude, $latitude, $altitude) = explode(","$xml->Response->Placemark->Point->coordinates);
 
   if(abs($longitude) > 0){
       
           $sql = "UPDATE jos_gmaps_markers SET latitude='$latitude', longitude='$longitude' WHERE id={$row['id']}";
           $res = mysql_query($sql);
           
           if(!$res){
               die(mysql_error());    
           }else{
               echo "Record updated. <br />"          }
           
           sleep(1);
           ob_flush();
           
   } }
?>