2015-07-10 97 views
0

我已将新数据添加到我的API。我想将它作为纯文本返回API数据返回HTML

这是PHP返回的API响应。

{ 
    "apiVersion":"1.0", 
    "data":{ 
      "location":"London",: 
      { 
      "pressure":"1021", 
       "temperature":"23", 
       "skytext":"Sky is Clear", 
       "humidity":"40", 
       "wind":"18.36 km/h", 
       "date":"07-10-2015", 
       "day":"Friday" 
      } 
     } 

我想返回我的html页面上的压力值,以便我的用户可以看到读数。我有问题显示它。

这是我的PHP api.php

require_once('./includes/config.php'); 
require_once('./includes/functions.php'); 
error_reporting(0); 
header('Content-Type: text/plain; charset=utf-8;'); 

$city = $_GET['city']; 

if(isset($city)) { 

    $weather = new Weather($conf['apikey'], $_GET['f']); 
    $weather_current = $weather->get($city, 0, 0, null, null); 

    $now = $weather->data(0, $weather_current); 

    if($now['location'] !== NULL) { 
     echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }'; 
    } else { 
     echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }'; 
    } 
} else { 
    echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }'; 
} 
+0

'{“apiVersion”:“1.0”,“data”:{“location”:“London”:{ “pressure”:“1021”,“temperature”:“23”,“skytext”是湿度“:”40“,”风“:”18.36公里/小时“,”日期“:”07-10-2015“, ”天“:”星期五“}} – Cyclonecode

+0

我展示了json结果,我仍然试图调试这只需要一点点帮助解决问题 – user3146197

+0

如果你可以提供更多的上下文,它会更容易帮助你。截至目前,我们几乎没有工作。 – AnotherGuy

回答

0

为了从一个JSON源获取数据,你应该与json_decode()方法分析数据。然后可以使用第二个参数将其解析为数组。如果你省略第二个参数,你会得到一个对象数组。

重要提示:看来你的JSON也有语法错误。在天气信息之前,我添加了一个weather密钥。

$data = '{ 
    "apiVersion":"1.0", 
    "data":{ 
     "location":"London", 
     "weather":{    // Notice the new key! 
      "pressure":"1021", 
      "temperature":"23", 
      "skytext":"Sky is Clear", 
      "humidity":"40", 
      "wind":"18.36 km/h", 
      "date":"07-10-2015", 
      "day":"Friday" 
     } 
    } 
}'; 

$json = json_decode($data, true); 

然后,您应该能够作为关联数组获取压力。

$pressure = $json['data']['weather']['pressure']; // Equals: 1021 

希望这能帮助你,快乐的编码!

0

首先,你需要验证你的JSON。它缺少一些关键的东西,使你无法解析它。使用JSONLint来验证您的JSON。

修改后的JSON,使之有效,我做了以下内容:

$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}'; 

$obj_style = json_decode($json); 
$array_style = json_decode($json, true); 

echo $obj_style->data->data->pressure; 
echo $array_style['data']['data']['pressure']; 

使用json_decode()我是能够建立一种方式来解析JSON两种方式,一旦作为一个对象,一次作为一个数组(添加true标志将结果作为数组返回)。

从那里你所要做的就是钻镇到你想要显示的信息位。