从json结果中提取一位数据

时间:2018-08-05 19:26:06

标签: php json curl

我正在尝试在加载CURL时从JSON数组中提取一位数据。从我可以告诉我是否回显结果的角度来看,它的加载情况很好,但是当我获得postal_town时,我总是遇到空白?我的PHP代码:

  $url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=52.406822,-1.519693&sensor=true";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $response_a = json_decode($response, true);
    $town = $response_a['results'][0]['address_components'][0]['types']['postal_town'];

    echo $town;

JSON结果的示例是:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Ringway Rudge",
               "short_name" : "A4053",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Coventry",
               "short_name" : "Coventry",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Coventry",
               "short_name" : "Coventry",
               "types" : [ "postal_town" ]
            },
            {
               "long_name" : "West Midlands",
               "short_name" : "West Midlands",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "England",
               "short_name" : "England",
               "types" : [ "administrative_area_level_1", "political" ]
            },

1 个答案:

答案 0 :(得分:1)

这可以解决问题,按德文所说的做了,谢谢

   $result = @file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=53.406822,-1.519693&sensor=true" );
    if ($result === FALSE) {
        //manage exception from file_get_contents call
    } else {
        $geocodedinfo = json_decode($result);
        if ($geocodedinfo->status == "OK") {
            $town = "";
            foreach ($geocodedinfo->results[0]->address_components as $addrcomps) {
                if ( $addrcomps->types[0] == 'postal_town')
                    $town = $addrcomps->long_name;           
            }
        }
    }


    echo $town;