简体   繁体   中英

PHP read weather feed from api.met.no

I am trying to read JSON from this https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=-16.516667&lon=-68.166667

$options = array(
    'http'=>array(
      'method'=>"GET",
      'header'=>"Accept-language: en\r\n" .
                "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad 
    )
);  

$context = stream_context_create($options);
$data_url = "https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=-16.516667&lon=-68.166667";

$json = file_get_contents($data_url,false,$context);

$data = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);


foreach ($data as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n<br>";
    } else {
        echo "$key => $val\n<br>";
    }
}

This works fine, but I need to select specific values according to the key, something like:

foreach ($data as $key) {
      echo $key["properties"] ["timeseries"] ["0-x"] ["data"] ["instant"] ["details"];
}

But of course that doesn't work for me. Please don't know how to do it? Thanks

Looking at the raw json return, the item you are trying to get is fairly buried, but you can still get to it easy enough. Example data return:

{
  "type": "Feature",
  "geometry": {
     ...
  },
  "properties": {
    "meta": {
       ...
    },
    "timeseries": [
        {
        "time": "2020-08-18T12:00:00Z",
        "data": {
          "instant": {
            "details": {
              "air_pressure_at_sea_level": 1018.4,
              "air_temperature": 4.7,
              "cloud_area_fraction": 92.2,
              "relative_humidity": 59.3,
              "wind_from_direction": 308.4,
              "wind_speed": 3.8
            }
         },
    ...

You can access that specific data with:

$json = file_get_contents($data_url,false,$context);

// This is all you need to turn json into a usable array
$data = json_decode($json,true); 

// Loop on the nested timeseries group:
foreach($data['properties']['timeseries'] as $ts) {
    
    // the time part of it
    $time    = $ts['time'];
    
    // get at it direct
    $var     = $ts['data']['instant']['details']['air_temperature'];

    // shorthand it if you wish:
    $details = $ts['data']['instant']['details'];
    $var     = $details['air_temperature'];
    
    // do whatever else you need to do with it
    echo $var;
    $array_of_temps[] = $var;
    // etc ...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM