我试图使用简单的天气API,但无论如何,它无论如何都不会将它识别为对象。这是我的代码:
$url = "https://www.amdoren.com/api/weather.php?api_key=za8LEJ8F9mcHK8SvLxdM98rM9mNFjW&lat=40.7127837&lon=-74.0059413";
$curl = curl_init($url);
$curl_response = curl_exec($curl);
$jsonobj = json_decode($curl_response);
$msg = "Temperature in ".$city."will be: ". $jsonobj->forecast->max_c;
这是我试图通过$jsonojb->forecast->max_c
:
{
"error" : 0,
"error_message" : "-",
"forecast":[
{"date":"2016-12-02",
"avg_c":8,
"min_c":5,
"max_c":11,
"avg_f":46,
"min_f":41,
"max_f":52,
(...)
但它不起作用。我做错了什么人?
答案 0 :(得分:2)
预测是一个数组,所以你必须这样使用:
$forecast = $jsonobj->forecast;
$forecast[0]->max_c;
答案 1 :(得分:1)
您可以尝试以下代码:
$url = "https://www.amdoren.com/api/weather.php?api_key=za8LEJ8F9mcHK8SvLxdM98rM9mNFjW&lat=40.7127837&lon=-74.0059413";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
$jsonobj = json_decode($curl_response);
$msg = "Temperature in ". $city . " will be: ". $jsonobj->forecast[0]->max_c;
echo $msg;
希望它有所帮助!