$user_id]; if (!empty($_GET['start_date'])) { $sql .= " AND expense_date >= :start_date"; $params['start_date'] = $_GET['start_date']; } if (!empty($_GET['end_date'])) { $sql .= " AND expense_date <= :end_date"; $params['end_date'] = $_GET['end_date']; } if (!empty($_GET['category'])) { $sql .= " AND category = :category"; $params['category'] = $_GET['category']; } $sql .= " ORDER BY expense_date DESC"; $stmt = $pdo->prepare($sql); $stmt->execute($params); $expenses = $stmt->fetchAll(PDO::FETCH_ASSOC); // Set headers for CSV download header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="despesas.csv"'); // Open output stream $output = fopen('php://output', 'w'); // Write CSV header fputcsv($output, ['Data', 'Descricao', 'Valor', 'Categoria']); // Write data if ($expenses) { foreach ($expenses as $expense) { fputcsv($output, [ $expense['expense_date'], $expense['description'], $expense['amount'], $expense['category'] ]); } } fclose($output); exit();