Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Send A POST Request To FAWN's Report Generator For CSV Data

DZone's Guide to

Send A POST Request To FAWN's Report Generator For CSV Data

·
Free Resource
The Report Generator form processor may change without notice, so it's recommended to use FAWN's published feeds, but this code works at the moment.

To figure out what content to send, request a report while the HTTP proxy Fiddler is recording. Select the request, click the Session Inspector tab, then the Forms tab. The "BODY" section will show you what needs to be given to http_build_query().


// Example using numeric presetRange (only allowed values are 3, 7, 14, and 30)
$postData = array(
    'locs__260' => 'on'
    ,'reportType' => 'daily'
    ,'vars__Rainfall' => 'on'
    ,'format' => '.CSV (Excel)'
    ,'presetRange' => '14'
);

// Example fetching custom number of days
$numDays = 52;
$toTime = strtotime('yesterday, 12PM'); // middle of day to avoid DST/TZ issues
$fromTime = strtotime('yesterday, 12PM - ' . $numDays . ' day');
$postData = array(
    'locs__260' => 'on'
    ,'reportType' => 'daily'
    ,'vars__Rainfall' => 'on'
    ,'format' => '.CSV (Excel)'
    ,'presetRange' => 'dates'
    ,'fromDate_m' => date('n', $fromTime)
    ,'fromDate_d' => date('j', $fromTime)
    ,'fromDate_y' => date('Y', $fromTime)
    ,'toDate_m' => date('n', $toTime)
    ,'toDate_d' => date('j', $toTime)
    ,'toDate_y' => date('Y', $toTime)
);

// make the request
$csvLines = file(
    'http://fawn.ifas.ufl.edu/data/reports/?res'
    ,false
    ,stream_context_create(array(
        'http' => array(
            'method' => 'POST'
            ,'header'  => 'Content-type: application/x-www-form-urlencoded'
            ,'content' => http_build_query($postData)
        )
    ))
);

array_shift($csvLines); // remove header line

foreach ($csvLines as $line) {
    // split and remove surrounding quotes between columns.
    // this is safe because commas will not appear in data.
    $parts = explode('","', $line);
    // reformat data for our purposes
    $data[] = array(
        'date' => date('Y-m-d', strtotime($parts[1]))
        ,'rain_in' => (float)$parts[2]
    );
}

var_export($data);
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}