function exportCSV($arr, $dbh) { if (isset($arr['reportType']) && $arr['reportType'] == 'summaryByUPC') { $wine = new Wine($dbh); $wine->fetchWineByUPC($arr['upc']); if (isset($arr['toDate']) && $arr['toDate'] != null) { $to = $arr['toDate']; } else { $to = null; } if (isset($arr['fromDate']) && $arr['fromDate'] != null) { $from = $arr['fromDate']; } else { $from = null; } $json = $wine->getInventorySummary($from, $to); //Generate HTML and echo it out; $data = json_decode($json, true); if (!isset($data[0])) { die('No data was found matching your criteria.'); } $fp = fopen($_SERVER['DOCUMENT_ROOT'] . '/tmp/summaryByUPC.csv', 'w'); $header = 'UPC,Name,Cost,SellingPrice,Quantity,DateTime,Location'; fwrite($fp, $header); fwrite($fp, PHP_EOL); foreach ($data as $row) { fputcsv($fp, $row); } fclose($fp); header('Location: /tmp/summaryByUPC.csv'); } else { if (isset($arr['reportType']) && $arr['reportType'] == 'completeInventory') { $wine = new Wine($dbh); if (isset($arr['toDate']) && $arr['toDate'] != null) { $to = $arr['toDate']; } else { $to = null; } $args = array('date' => $to); $wines = $wine->fetchAllWines(); $data = json_decode($wines, true); $fp = fopen($_SERVER['DOCUMENT_ROOT'] . '/tmp/completeInventory.csv', 'w'); $header = 'UPC,Name,Qty,Cost/Bottle,Total Cost,Selling Price,Cost/Selling Price'; fwrite($fp, $header); fwrite($fp, PHP_EOL); foreach ($data as $row) { $curWine = new Wine($dbh); $curWine->fetchWineByUPC($row['upc']); $args = array('date' => $to); $inv = $curWine->getCurrentInventory($args); //cur is json summary of inventory $row = '' . $curWine->getUPC() . ',' . $curWine->getName() . ',' . $curWine->getCurrentInventory($args) . ',' . number_format($curWine->getCost(), 2, '.', '') . ',' . number_format($curWine->getCurrentInventory($args) * $curWine->getCost(), 2, '.', '') . ',' . number_format($curWine->getSellPrice(), 2, '.', '') . ',' . $curWine->getCost() / $curWine->getSellPrice(); fwrite($fp, $row); fwrite($fp, PHP_EOL); } fclose($fp); header('Location: /tmp/completeInventory.csv'); } else { die('Invalid Report Type'); } } }