0

JSON:

{"location":{"name":"Tirana","region":"Tirane","country":"Albania","lat":41.33,"lon":19.82,"tz_id":"Europe/Tirane","localtime_epoch":1484543668,"localtime":"2017-01-16 5:14"},"current":{"last_updated_epoch":1484543668,"last_updated":"2017-01-16 05:14","temp_c":4.0,"temp_f":39.2,"is_day":0,"condition":{"text":"Overcast","icon":"//cdn.apixu.com/weather/64x64/night/122.png","code":1009},"wind_mph":6.9,"wind_kph":11.2,"wind_degree":150,"wind_dir":"SSE","pressure_mb":1009.0,"pressure_in":30.3,"precip_mm":0.0,"precip_in":0.0,"humidity":60,"cloud":0,"feelslike_c":1.2,"feelslike_f":34.2}}

PHP:

$response = file_get_contents('http://api.apixu.com/v1/current.json?key=a54959ce2b294134bda34330171601&q=Paris');
var_dump(json_decode($response)); 
echo $response->location[0]->name; 

API Call: http://api.apixu.com/v1/current.json?key=a54959ce2b294134bda34330171601&q=Tirana

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Rei Koleci
  • 11
  • 2
  • How about capturing the `json_decode($response` to a local variable, and then parsing the json ? – karthikr Jan 16 '17 at 04:29
  • Location is a single dimensional array, not a multi-dimensional array. so remove the `[0]` -> `echo $response->location->name;` – Sean Jan 16 '17 at 04:32
  • just a thought: you shouldn't provide links containing a valid API key, even if the basic service is free. you should, however, get that key exchanged for a new one. (and also, since the key is embedded in the URL, you should use HTTPS in the future) – Franz Gleichmann Jan 16 '17 at 07:02

2 Answers2

4

Try like this.You get the contents in json format.Use json_decode() with second parameter true to convert into array.

<?php
$json = '{"location":{"name":"Tirana","region":"Tirane","country":"Albania","lat":41.33,"lon":19.82,"tz_id":"Europe/Tirane","localtime_epoch":1484543668,"localtime":"2017-01-16 5:14"},"current":{"last_updated_epoch":1484543668,"last_updated":"2017-01-16 05:14","temp_c":4.0,"temp_f":39.2,"is_day":0,"condition":{"text":"Overcast","icon":"//cdn.apixu.com/weather/64x64/night/122.png","code":1009},"wind_mph":6.9,"wind_kph":11.2,"wind_degree":150,"wind_dir":"SSE","pressure_mb":1009.0,"pressure_in":30.3,"precip_mm":0.0,"precip_in":0.0,"humidity":60,"cloud":0,"feelslike_c":1.2,"feelslike_f":34.2}}
';
$array = json_decode($json,true);
//print_r($array);
$location = $array['location'];
echo $location['name'];

?>
Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19
1

use json_decode to parse the json string to array, then access it with the index.

the demo

$response = file_get_contents('http://api.apixu.com/v1/current.json?key=a54959ce2b294134bda34330171601&q=Paris');
$array = json_decode($response, true); 
echo $array['location']['name']; 
LF00
  • 27,015
  • 29
  • 156
  • 295