Need some API / php help

First post (I am probably using the wrong terms, be gentle),
I have tried some searches, but not knowing what terms to use, I am coming up empty.

I am trying to use the API to pull data into a MariaDB. I have done this with a different weather station manufactures API, so I know it works.
When I try to read the string and assign it to variables, I don’t get the expected results. It must be how I have things in my foreach loop formatted. (here is a snippet of the code in question:)

$apiString = 'https://swd.weatherflow.com/swd/rest/observations/station/[sanitized_station_id]?token=[sanitized_token]';
$json = file_get_contents($apiString);

//convert json object to php associative array
$data = json_decode($json, true);

// Loop through the array
foreach ($data as $row)
  {
    $station_id = $row['station_id'];

 $sql = "INSERT INTO $tableName
  (
    `Station_Name`
  )

  VALUES
    (
      '$station_id'
    )";

  echo "$sql<br />";
  }

(The echo statement gives me the following output:)

INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘L’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘L’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘A’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘’ )
INSERT INTO TempestWeatherData ( Station_Name ) VALUES ( ‘’ )

I should only have one “Insert Into” statement (not 12) and the “Value” should have the ‘station_id’ rather that an empty value.

Can anybody point me in the right direction to get my “foreach” section formatted correctly?
Maybe some code examples.

Thanks!
Scott

Add an echo of $data above your foreach loop, and an echo of $row within your loop so we can see what the data looks like.

I will have to get that info worked up in a bit, but, I did get it to only display one line (instead of 12).
BUT, I am only getting one value (the first on, station_name) back.
I feel it has something to do with my formatting.
i.e.

$air_temperature = $data['air_temperature'];

Like I need more brackets or curly braces.

Thanks,
Scott

I may have found my solution.
I need to do some more testing, but this got me going in the right direction:

$air_temperature = $data['obs']['0']['air_temperature'];

Thanks,
Scott

well of course, you need to follow the API’s data structure…

Yeah…
I had that set up correctly (this morning :confused: )and took it out to test something and neglected to put it back.
It’s the simple things…

Thanks,
Scott

3 Likes