使用 PHP 将气象站 API URL 转换为 csv

我正在尝试使用我的气象站的 API,据我所知是 JSON 格式,并转换为 csv 文件。


API返回:


[{"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]}}}}]

通过 wtools.io/convert-json-to-php-array 格式化的代码

网页代码:


<?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);

文件已创建,但我没有获得正确的数据。评论/想法将不胜感激。


xx:xx:xx:xx:xx:xx,数组,数组


千巷猫影
浏览 82回答 1
1回答

手掌心

您需要展平数组(意味着将每个值放入第一个维度)。应用于您的示例,您需要这样的东西:$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));$csvArray = [];foreach($iterator as $value) {    $csvArray[] = $value;}fputcsv($fp, $csvArray);工作示例。编辑 - 更具可读性的数组扁平化器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 linefputcsv($fp, $csvArray);工作示例。
打开App,查看更多内容
随时随地看视频慕课网APP