2017-01-16 81 views
-1

JSON:如何使用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}} 

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調用:http://api.apixu.com/v1/current.json?key=a54959ce2b294134bda34330171601&q=Tirana

+0

如何捕獲'json_decode($ response'到本地變量,然後解析JSON? – karthikr

+0

地點是一維陣列,而不是一個多維數組。所以刪除'[0]' - >'echo $ response-> location-> name;' – Sean

+0

只是一個想法:即使基本服務是免費的,你也不應該提供包含有效API密鑰的鏈接,但是你應該將該密鑰交換爲新的(並且,由於密鑰嵌入在URL中,所以將來應該使用HTTPS) –

回答

0

使用json_decode解析JSON字符串數組,然後用索引來訪問它。

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']; 
0

嘗試像this.You與第二參數true獲得的內容在json format.Use json_decode()轉換成陣列。

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

?> 
相關問題