1

I am trying to echo a value from google map json url. I can var_dump() the keys and the values but I can't pull the specific value alone. Php code:

<?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>';

?>

The var_dump() result is as follows;

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

I need to assign distance->text to a php variable. Could anyone help?

2

2 Answers 2

1

Try this:

$variable = json_decode($data)->rows[0]->elements[0]->distance->text;
Sign up to request clarification or add additional context in comments.

Comments

0

In order to convert the json to a php array variable you can use json_decode($data, true) with the second parameter to true, to convert it to an associative array.

code example.

$json = json_decode($date,true);

print  $jsonp['rows'][0]['elements']['0']['distance']['value'];

Doc. http://php.net/manual/en/function.json-decode.php

Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.