0

I have the following json format data :

{"query":{
  "count":5,"created":"2014-12-19T15:42:41Z","lang":"en-US","results":{
    "channel":[{
      "item":{
        "forecast":{"date":"19 Dec 2014","high":"61","low":"47"}
       }},{
      "item":{
        "forecast":{"date":"20 Dec 2014","high":"60","low":"48"}
       }},{
      "item":{
        "forecast":{"date":"21 Dec 2014","high":"61","low":"44"}
       }},{
      "item":{
        "forecast":{"date":"22 Dec 2014","high":"58","low":"46"}
       }},{
      "item":{
        "forecast":{"date":"23 Dec 2014","high":"58","low":"45"}
       }}]
     }
   }
}

How can I access specific data from this format (for example only high and low), in order to insert these data in a mySQL database for instance?

Paebbels
  • 15,573
  • 13
  • 70
  • 139
george123
  • 33
  • 1
  • 8
  • have you even googled? here http://stackoverflow.com/questions/263392/handling-data-in-a-php-json-object – dsharew Dec 19 '14 at 15:57
  • you don't "extract from json". you decode the json to a native data structure, and work with that. – Marc B Dec 19 '14 at 16:01

3 Answers3

1

Put your json in a variable $str for example, than you can access the items :

$json = json_decode($str);
$res = $json->{'query'}->{'results'}->{'channel'};
foreach($res as $ch) {
    echo "High:" . $ch->{'item'}->{'forecast'}->{'high'} . "<br>";
    echo "Low:" . $ch->{'item'}->{'forecast'}->{'low'} . "<br>";
}
Alex
  • 626
  • 7
  • 16
0

Use json_decode to turn it into an array:

$array = json_decode($json_data, true);

Then, you can access the items, forecast, and high/low values:

$high = $array[1]['item']['forecast']['high'];
Community
  • 1
  • 1
kainaw
  • 4,256
  • 1
  • 18
  • 38
  • Add the second param if you want it to return an array. json_decode($data, true) otherwise its an object – pdizz Dec 19 '14 at 16:19
0

Assuming your json string is the variable $json:

$data = json_decode($json);
$channels = $data->query->results->channel;
foreach($channels as $channel) {
    // DO SOMETHING HERE
    die($channel["item"]["high"]);
}
Varedis
  • 738
  • 5
  • 14