2016-11-28 46 views
0

好吧,我有一些麻煩理解如何使用露天天氣API。 我一直在使用它作爲PHP OpenWeather

<?php 
    $request = file_get_contents('http://api.openweathermap.org/data/2.5/forecast/city?id=myidblablabla'); //example ID 

    $jsonPHP = json_decode($request); 

    echo $jsonPHP->city; 

?> 

嘗試,但我得到一個錯誤說

Catchable fatal error: Object of class stdClass could not be converted to string in

現在有1個更多的問題,我要問,我怎麼得到某些碼城市氣溫,溼度等?從我收到的代碼我只得到莫斯科

+0

那麼這些文檔對你來說並不重要? –

+0

天氣現在已經在開源許可下發布了嗎?這是個好消息! – arkascha

+0

有點兒,找不到100%準確的答案。我試圖調查它,但我的每一個嘗試都是失敗 –

回答

1

爲了簡化它,您也可以將json轉換爲數組。

$jsonPHP = json_decode($request,true); 

現在讓我們簡單討論一下。根據文檔(http://openweathermap.org/current),

還要注意我從來沒有之前使用這個API。我只是想在這裏幫忙。

如果碰到api.openweathermap.org/data/2.5/weather?lat=35&lon=139

它響應爲

{"coord":{"lon":139,"lat":35}, 
"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049}, 
"weather":[{"id":804,"main":"clouds","description":"overcast clouds","icon":"04n"}], 
"main":{"temp":289.5,"humidity":89,"pressure":1013,"temp_min":287.04,"temp_max":292.04}, 
"wind":{"speed":7.31,"deg":187.002}, 
"rain":{"3h":0}, 
"clouds":{"all":92}, 
"dt":1369824698, 
"id":1851632, 
"name":"Shuzenji", 
"cod":200} 

現在,假設你要取天氣溼度,它只是:

天氣:

echo $jsonPHP["weather"][0]["id"]; 

溼度:

echo $jsonPHP["main"]["humidity"]; 

還要注意的是,如果你打http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139並得到響應爲

{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."} 

對於情況下,他們已經在這裏解釋:

http://openweathermap.org/faq#error401它是:

Q: API calls return an error 401

A: Starting from 9 October 2015 our API requires a valid APPID for access. Note that this does not mean that our API is subscription-only now - please take a minute to register a free account to receive a key.

We are sorry for inconvenience but this is a necessary measure that will help us deliver our services to you faster and more reliably.

For FOSS developers: we welcome free and open source software and are willing to help you. If you want to use OWM data in your free software application please register an API key and file a ticket describing your application and API key registered. OWM will review your request lift access limits for your key if used in open source application.

+0

是的,但是當我使用$ jsonPHP [「weather」] [0] [「id」];我得到未定義的索引:weather –

+1

您忘記我無法訪問http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139,因爲我沒有* APPID *,所以我做了一個模擬響應,將其保存爲* json *文件,並獲得正確的輸出。我得到'804',這是正確的! –

+0

是的,但這是你實際從var_dump得到的http://pastebin.com/KteUqtqc我試圖訪問[list] [0] ['weather'],它的工作原理就是我不能將它轉換成字符串 –