0

I am developing a system to get values from gGoogle Api Elevation with PHP. I have it working and when I get the value it returns as String in this format:

{ "results" : [ { "elevation" : 914.033935546875, "location" : { "lat" : -25.4499861, "lng" : -49.2339611 }, "resolution" : 152.7032318115234 } ], "status" : "OK" }       

I want to get the value of the elevation in this result, can you help me to do this? thanks you.

jottbe
  • 4,228
  • 1
  • 15
  • 31
Gouveia
  • 29
  • 6
  • You probably have to parse the string as a JSON document. – jottbe Jul 28 '19 at 20:33
  • yeas i did, it becomes an array with this format: Array ( [results] => Array ( [0] => Array ( [elevation] => 914.03393554688 [location] => Array ( [lat] => -25.4499861 [lng] => -49.2339611 ) [resolution] => 152.70323181152 ) ) [status] => OK ) – Gouveia Jul 28 '19 at 20:44

1 Answers1

0

The string is in JSON format.

You can use json_decode to convert it to a PHP array.

$json_string = <<<JSON
{
  "results": [
    {
      "elevation": 914.033935546875,
      "location": {
        "lat": -25.4499861,
        "lng": -49.2339611
      },
      "resolution": 152.7032318115234
    }
  ],
  "status": "OK"
}
JSON;

$array = json_decode($json_string, TRUE);
echo $array['results'][0]['elevation'];

Output:

914.03393554688
cam8001
  • 1,581
  • 1
  • 11
  • 22
  • hello, i tried this solution, but it gives me an error: Fatal error: Uncaught Error: Cannot use object of type stdClass as array – Gouveia Jul 28 '19 at 20:37
  • if i add true in the json_decode: $result = json_decode($response, true); echo $result[0]['elevation']; it gives me this error: Notice: Undefined offset: 0 in ... – Gouveia Jul 28 '19 at 20:39
  • Hi Gouveia, I will be at my desk soon and will write a more complete (and correct) answer. :) – cam8001 Jul 28 '19 at 20:42
  • when i use the funcion json_decode, it becomes an array in thsi format: Array ( [results] => Array ( [0] => Array ( [elevation] => 914.03393554688 [location] => Array ( [lat] => -25.4499861 [lng] => -49.2339611 ) [resolution] => 152.70323181152 ) ) [status] => OK ) – Gouveia Jul 28 '19 at 20:43
  • your answer worked! thanks you very much for your atention. – Gouveia Jul 28 '19 at 21:11