0

I am trying to use the API from my weather station, from what I am told is in JSON format, and convert to csv file.

API return:

[{"macAddress":"xx:xx:xx:xx:xx:xx","lastData":{"dateutc":1595258880000,"tempinf":74.3,"humidityin":44,"baromrelin":29.929,"baromabsin":29.235,"tempf":85.5,"battout":1,"humidity":62,"winddir":167,"windspeedmph":0.2,"windgustmph":1.1,"maxdailygust":9.2,"hourlyrainin":0,"eventrainin":0,"dailyrainin":0,"weeklyrainin":0,"monthlyrainin":0.571,"totalrainin":1.823,"solarradiation":832.38,"uv":8,"feelsLike":90.84,"dewPoint":70.96,"feelsLikein":73.5,"dewPointin":51,"tz":"America/Chicago","date":"2020-07-20T15:28:00.000Z"},"info":{"name":"My
Weather
Station","coords":{"coords":{"lon":134.65635809999999,"lat":32.6587316},"address":"100
Park Lane, Yourtown, TN 77777,
USA","location":"Yourtown","elevation":146.7066497802734,"geo":{"type":"Point","coordinates":[134.65635809999999,32.6587316]}}}}]

Code formatted via wtools.io/convert-json-to-php-array

array (   0 =>    array (
    'macAddress' => 'xx:xx:xx:xx:xx:xx',
    'lastData' => 
    array (
      'dateutc' => 1595258880000,
      'tempinf' => 74.3,
      'humidityin' => 44,
      'baromrelin' => 29.929,
      'baromabsin' => 29.235,
      'tempf' => 85.5,
      'battout' => 1,
      'humidity' => 62,
      'winddir' => 167,
      'windspeedmph' => 0.2,
      'windgustmph' => 1.1,
      'maxdailygust' => 9.2,
      'hourlyrainin' => 0,
      'eventrainin' => 0,
      'dailyrainin' => 0,
      'weeklyrainin' => 0,
      'monthlyrainin' => 0.571,
      'totalrainin' => 1.823,
      'solarradiation' => 832.38,
      'uv' => 8,
      'feelsLike' => 90.84,
      'dewPoint' => 70.96,
      'feelsLikein' => 73.5,
      'dewPointin' => 51,
      'tz' => 'America/Chicago',
      'date' => '2020-07-20T15:28:00.000Z',
    ),
    'info' => 
    array (
      'name' => 'My Weather Station',
      'coords' => 
      array (
        'coords' => 
        array (
          'lon' => 134.65635809999999,
          'lat' => 32.6587316,
        ),
        'address' => '100 Park Lane, Yourtown, TN 77777, USA',
        'location' => 'Yourtown',
        'elevation' => 146.7066497802734,
        'geo' => 
        array (
          'type' => 'Point',
          'coordinates' => 
          array (
            0 => 134.65635809999999,
            1 => 85.7601302,
          ),
        ),
      ),
    ),   ), )

Web page code:

<?php // Read JSON file 
$readjson = file_get_contents("https://weather_api") ;

//Decode JSON 
$data = json_decode($readjson, true);

//Print data 
print_r($data); echo "<br/><br/> Weather Stats are: <br/>";

//function to convert to csv file 

//Give our CSV file a name. 
$csvFileName = 'example.txt';   
//Open file pointer. 
$fp = fopen($csvFileName, 'w');   
//Loop through the associative array. 
foreach($data as $row){
    //Write the row to the CSV file.  
    fputcsv($fp, $row); 
}
//Finally, close the file pointer. 
fclose($fp);

The file is created but I am not getting the correct data. Comments/thoughts would be appreciated.

xx:xx:xx:xx:xx:xx,Array,Array

Machavity
  • 30,841
  • 27
  • 92
  • 100
SQLAJ
  • 13
  • 2

1 Answers1

0

You need to flatten your array (means put every value to the first dimension).

Have a look at this.

Applied to your example you'd need something like this:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$csvArray = [];
foreach($iterator as $value) {
    $csvArray[] = $value;
}

fputcsv($fp, $csvArray);

Working example.

Edit - more readable array flattener

function getFlatArray($data, $keyPrefix = '') {
    $result = [];
    
    foreach ($data as $key => $value) {
        $newKey = $keyPrefix . $key;
        
        if (!is_array($value)) {
            $result[$newKey] = $value;
        } else {
            $result += getFlatArray($value, $newKey . '-');
        }
    }
    
    return $result;
}

$csvArray = getFlatArray(array_pop($data));

fputcsv($fp, array_keys($csvArray)); // add keys to first line
fputcsv($fp, $csvArray);

Working example.

SirPilan
  • 4,649
  • 2
  • 13
  • 26
  • I need the key and value in the list. I have been reviewing your code and reference but it is just not clicking. Still researching and testing. Thanks for the help. – SQLAJ Jul 21 '20 at 12:09
  • Do you want the keys in the first line of the csv? - Thats how its normally done. I can provide a more human readable example. – SirPilan Jul 21 '20 at 12:35
  • That would be awesome and should work. It will be used to import into a database. – SQLAJ Jul 21 '20 at 13:17
  • Wow. This is more than I was thinking. Thanks for the help. – SQLAJ Jul 21 '20 at 16:41