1

I'm having an issue with special characters for addresses from my database for google geocode, but not if I hardcode them.

Simple geocode code

$url = "http://maps.googleapis.com/maps/api/geocode/json?address=". $address . "&sensor=true";      
$jsonfile = file_get_contents($url);
$jsondata = json_decode($jsonfile);
$lat = $jsondata->results[0]->geometry->location->lat;
$lng = $jsondata->results[0]->geometry->location->lng;

This code works for standard addresses but doesn't work when the address has a special character in it IF it comes from my database.

If I hardcode the address as:

$address = "10 Montée de Clausen, 1343 Luxemburg City, Luxembourg";
$address = str_replace(" ","+",$address);

The code works. If the address comes from my database

$query="SELECT * FROM mytable";
$result=mysqli_query($GLOBALS["___mysqli_ston"], $query);
while($row=mysqli_fetch_assoc($result)){
    $address = $row['address'];
    $address = str_replace(" ","+",$address);
    // geocode code.
}

It doesn't work.

Database is in utf8_unicode_ci. If I echo the $url including the address even if it has come from my database, and then put that url into a browser the url actually spits out the right data but using that url in my code doesn't work.

I've tried to url encode the address before the str_replace and also after the str_replace and it still doesn't work.

How do I get it to work?

j0k
  • 22,600
  • 28
  • 79
  • 90
user2484214
  • 143
  • 1
  • 3
  • 12

2 Answers2

2

What if, you do the following:

$query="SELECT * FROM mytable";
$result=mysqli_query($GLOBALS["___mysqli_ston"], $query);
while($row=mysqli_fetch_assoc($result)){
    $address = urlencode(mb_convert_encoding($row['address'], 'UTF-8'));
    // geocode code...
}
anupam
  • 756
  • 5
  • 11
  • Thank you very much. I thought it had something to do with the encoding but had no idea how to fix it. Again, thanks! – user2484214 Sep 20 '13 at 09:57
1

Try urlencode for database output data

Like

 $address = urlencode($row['address'])

Also remove this $address = str_replace(" ","+",$address); from current code.

Hariprasad Prolanx
  • 2,762
  • 1
  • 16
  • 13