DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Steve has posted 12 posts at DZone. View Full User Profile

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

01.23.2009
| 2786 views |
  • submit to reddit
        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);