include_once('/var/www/html/illinoiselectiondata/Simple_HTML_Dom/simple_html_dom.php');
$FileName = '2015MayorApril.csv';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename='.$FileName);
$output = fopen('php://output', 'w');
$Fields = array('Ward', 'Precinct', 'Emanuel', 'Emanuel %', 'Garcia', 'Garcia %', 'Total');
fputcsv($output, $Fields);
$url = "http://www.chicagoelections.com/en/pctlevel3.asp?elec_code=9&race_number=10&Ward=";
for ($i = 1; $i < 51; $i++) {
$fields = array (
"D3" => "Mayor",
"VTI-GROUP" => "0",
"flag" => "1",
"B1" => " View The Results "
);
$fields_string = '';
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url.$i);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//this option returns the resuls rather than automatically echos the response
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
$html = str_get_html($result);
$r = 1;
$n = array();
foreach($html->find('tr') as $row) {
if ($r > 3 ) {
$n['Precinct'] = $row->find('td',0)->plaintext;
if ($n['Precinct'] == 'Total') {
break;
}
$n['Total'] = $row->find('td',1)->plaintext;
$n['Emanuel'] = $row->find('td',2)->plaintext;
$n['EmanuelPct'] = $row->find('td',3)->plaintext;
$n['Garcia'] = $row->find('td',4)->plaintext;
$n['GarciaPct'] = $row->find('td',5)->plaintext;
fputcsv($output, array($i, $n['Precinct'], $n['Emanuel'], $n['EmanuelPct'], $n['Garcia'], $n['GarciaPct'], $n['Total']));
}
$r++;
}
}
?>