-
Notifications
You must be signed in to change notification settings - Fork 0
/
snow_data.php
executable file
·70 lines (59 loc) · 2.89 KB
/
snow_data.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
include 'functions.php';
date_default_timezone_set('America/New_York');
$states = array('az', 'cal', 'co', 'id', 'nv', 'nm', 'or', 'utah', 'wa', 'wy');
$url_base = "http://www.wcc.nrcs.usda.gov/nwcc/rgrpt?station=";
foreach($states as $state) {
if (($handle = fopen("snow/".$state."_snow.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if(preg_match('/Site_Name/', $data[0])) { continue; }
$ch = curl_init($url_base . $data[1] . '&report=snowmonth_hist');
$name = strtolower(preg_replace('/(\(|\)|#|\s|\')/', '_', trim($data[0]) . '-' . $data[2]));
$fp = fopen("raw_data/".$state."_snow/" . $name . ".csv", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);
curl_close($ch);
fclose($fp);
echo $name . " processed\n";
}
fclose($handle);
}
$base_file = file("snow/".$state."_snow.csv");
$path = 'raw_data/' . $state . '_snow';
$files = scandir($path);
foreach($files as $file) {
if(!preg_match('/^\./', $file)) {
$site = preg_split('/-+/', $file);
$name = ucwords(str_replace('_', ' ', $site[0]));
$provider = explode('.', $site[1]);
$provider = strtoupper(substr_replace($provider[0], '', -1));
$fh = fopen('data/' . $state . '_snow/' . $file, "wb");
fputcsv($fh, array('location', 'snow_depth', 'snow_water_equivalent', 'provider', 'date'));
if (($handle = fopen($path . '/' . $file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if(preg_match('/^\d{4}/', $data[0]) && $data[0] >= 2000) {
$year = $data[0];
array_shift($data);
$unique_measurements = array_chunk($data, 3);
foreach($unique_measurements as $measurement) {
if(!preg_match('/^[A-Z]/', $measurement[0])) { continue; }
$date = date('m/Y', strtotime(strtolower($measurement[0]) . ' ' . $year));
if(preg_match('/^(10|11|12)/', $date)) {
echo "Old date " .$date . "\n";
$datebits = preg_split('/\//', $date);
$date = $datebits[0] . '/' . ($datebits[1] - 1);
echo "New Date $date\n";
}
fputcsv($fh, array($name, $measurement[1], $measurement[2], $provider, $date));
}
}
}
fclose($handle);
}
fclose($fh);
}
$file . " processed\n";
}
}