星期三 , 22 1 月 2025

hr system 系统 csv导出函数修改版 防止中文乱码

添加了: // Add BOM (Byte Order Mark) for Excel to recognize UTF-8
echo “\xEF\xBB\xBF”; // Set headers for CSV file download
header(‘Content-Type: text/csv; charset=utf-8’); // Set the output stream encoding to UTF-8
stream_filter_append($output, ‘convert.iconv.utf-8/utf-8//TRANSLIT’);

// Function to export table to CSV
function exportToCSV($conn, $table) {
    // Set headers for CSV file download
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $table . '_export.csv"');

    // Add BOM (Byte Order Mark) for Excel to recognize UTF-8
    echo "\xEF\xBB\xBF";

    // Open output stream
    $output = fopen('php://output', 'w');

    // Set the output stream encoding to UTF-8
    stream_filter_append($output, 'convert.iconv.utf-8/utf-8//TRANSLIT');

    // Get column names
    $sql = "SHOW COLUMNS FROM $table";
    $result = $conn->query($sql);
    $columns = array();
    while ($row = $result->fetch_assoc()) {
        $columns[] = $row['Field'];
    }

    // Write column names to CSV
    fputcsv($output, $columns);

    // Get data and write to CSV
    $sql = "SELECT * FROM $table";
    $result = $conn->query($sql);
    while ($row = $result->fetch_assoc()) {
        fputcsv($output, $row);
    }

    fclose($output);
    exit();
}