代码之家  ›  专栏  ›  技术社区  ›  Dalyan

来自google map json url的php echo值

  •  0
  • Dalyan  · 技术社区  · 6 年前

    我正在尝试从google map json url回显一个值。我可以var_dump()键和值,但不能单独提取特定值。PHP代码:

    <?php
        $from = 'Piccadilly+Circus+London+UK';
        $to = 'Brighton+Railway+Station+Brighton+UK';
        $json ='https://maps.googleapis.com/maps/api/distancematrix/json?origins='.$from.'&destinations='.$to.'&mode=driving&key=APIKEY';
        $ch = curl_init($json);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
    
        // Print Result
        echo '<pre>' . var_dump($data) . '</pre>';
    
    ?>
    

    var_dump()结果如下;

           string(542) "{
           "destination_addresses" : [ "Brighton, Queens Rd, Brighton BN1 3XP, UK" ],
           "origin_addresses" : [ "Piccadilly Circus, London W1B, UK" ],
           "rows" : [
              {
                 "elements" : [
                    {
                       "distance" : {
                          "text" : "86.7 km",
                          "value" : 86665
                       },
                       "duration" : {
                          "text" : "1 hour 59 mins",
                          "value" : 7114
                       },
                       "status" : "OK"
                    }
                 ]
              }
           ],
           "status" : "OK"
        }
        "
    

    我需要分配 距离->文本 一个php变量。有人能帮忙吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   toh19    6 年前

    试试这个:

    $variable = json_decode($data)->rows[0]->elements[0]->distance->text;
    
        2
  •  0
  •   Vidal    6 年前

    为了将json转换为php数组变量,可以使用 json_decode($data, true) 如果第二个参数为true,则将其转换为关联数组。

    代码示例。

    $json = json_decode($date,true);
    
    print  $jsonp['rows'][0]['elements']['0']['distance']['value'];
    
    

    博士。 http://php.net/manual/en/function.json-decode.php

    希望有帮助。