How do I get data in JSON from a URL

Using the JSON from this URL(weather station data stored): https://dataproxy.mtcc.ie/v1.5/api/fs/weather_polygons

How do I get the data for the station "N25 Midleton Bypass"?

I can process the URL, just down know how can I echo the data?

My coding is:

  $json_string = 'https://dataproxy.mtcc.ie/v1.5/api/fs/weather_polygons';
  $jsondata = file_get_contents($json_string);
  $obj = json_decode($jsondata, true);
  var_dump($obj);

The Json data I am expecting to get is something like that:

    ["wind_speed"]=>
    float(0.9)
    ["name"]=>
    string(19) "N25 Midleton Bypass"
    ["air_temperature_legend"]=>
    string(7) "14 - 16"
    ["maximum_wind_speed"]=>
    float(2.6)
    .........

I need to get the "0.9", "14 - 16", "2.6" to save into my weather database. Thanks!

Upvotes: 0

Views: 100

Answers (2)

arielnmz
arielnmz

Reputation: 9155

just down know how can I echo the data?

As the var_dump function tells you, you can access your data by simply accessing its fields, like this:

// echo wind_speed
echo $obj->wind_speed;

// echo name
echo $obj->name

// echo air_temperature_legend
echo $obj->air_temperature_legend;

// echo maximum_wind_speed
echo $obj->maximum_wind_speed;

On some recent PHP builds you can even use it like an associative array, with the keys being the fields of your object, just by simply casting your object:

$arr = (array)$obj;
echo $arr['wind_speed'];
echo $arr['name'];

how can get get these data only from the "name = N25 Midleton Bypass"

foreach ($objects as $obj) {
    if ($obj->name == 'N25 Midleton Bypass') {
        echo $obj->wind_speed;
        echo $obj->name
        echo $obj->air_temperature_legend;
        echo $obj->maximum_wind_speed;
    }
}

You can even go a little further and design a function that accepts the name you want to filter as a parameter:

function printStationInfo($objects, $station) {
    foreach ($objects as $obj) {
        if ($obj->name == $station) {
            echo $obj->wind_speed;
            echo $obj->name
            echo $obj->air_temperature_legend;
            echo $obj->maximum_wind_speed;
        }
    }
}

And use it like this:

printStationInfo($objects, 'N25 Midleton Bypass');

Upvotes: 0

Dustin Butler
Dustin Butler

Reputation: 897

You'll need to loop through the data to get the station your after then break out of the loop. Or if you want properties for all stations can use $properties within the loop

foreach($obj['features'] as $feature) {
  if ($feature['properties']['name'] == 'N25 Midleton Bypass') {
    $properties = $feature['properties'];
    break;
  }
}

echo $properties['wind_speed'];
echo $properties['name'];
echo $properties['air_temperature_legend'];
echo $properties['maximum_wind_speed'];

Upvotes: 1

Related Questions