google geocode not working for addresses with special characters from database

一笑奈何 提交于 2019-12-02 12:46:49

问题


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?


回答1:


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...
}



回答2:


Try urlencode for database output data

Like

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

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



来源:https://stackoverflow.com/questions/18912959/google-geocode-not-working-for-addresses-with-special-characters-from-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!