使用来自Google地理编码API的PHP获取JSON数据

时间:2016-06-14 12:00:31

标签: php json api google-maps

我得到的第一个错误是"Call to undefined function get_file_contents() on line 18",我试图在文件的开头定义get_file_contents()。错误消失,但echo $lat;

中没有显示任何内容
<?php 
    require_once('../db.php');
    $api_key = "somekey";
    $sqlQuery = mysql_query("SELECT `County` FROM `table`"); 



    /* Fetch county */ 
    while ($rows = mysql_fetch_array($sqlQuery))  { 
        $countyArr = $rows['County']; 

        /* Call google API and save coordinates for each county */ 
        $json = get_file_contents("https://maps.googleapis.com/maps/api/geocode/json?address=".$countyArr.",+CA&key=".$api_key."");
        $obj = json_decode($json);
        if ($obj->status == "OK") {
            $lat = $obj->results->location->lat;
            $lng = $obj->results->location->lng;

            echo $lat;
        }
    }
?>

这是我正在使用的API: https://developers.google.com/maps/documentation/geocoding/get-api-key

编辑: 该错误可能是由Godaddy的服务器上的php.ini设置引起的,用于共享主机。我试图在我在根文件夹中找到的php.ini中添加"allow_url_fopen = On",尽管它仍然不起作用。

1 个答案:

答案 0 :(得分:0)

<?php 

require_once('../db.php');

$api_key = "somekey";

$sqlQuery = mysql_query("SELECT `County` FROM `table`"); 



/* Fetch county */ 

while($rows = mysql_fetch_array($sqlQuery))  { 

    $countyArr = $rows['County']; 



    /* Call google API and save coordinates for each county */ 

    $json = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address=".$countyArr.",+CA&key=".$api_key."");

    $obj = json_decode($json);



    if ($obj->status == "OK") {

        $lat = $obj->results->location->lat;
        $lng = $obj->results->location->lng;

        echo $lat;




    }

}

?>
try file_get_contents this function