Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.9 kB
2
Indexable
Never
function export_data_to_csv() {
    if (isset($_POST['export_csv'])) {
		
        if (!current_user_can('manage_options')) {
            wp_die('Brak uprawnień.');
        }

		ob_clean();
		
        global $wpdb;
        $table_name = $wpdb->prefix . 'dystrybucja';

        $sql = "SELECT * FROM {$table_name}";
        $results = $wpdb->get_results($sql, ARRAY_A); 

        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="dane.csv"');

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

        $delimiter = ';';

        $column_headers = array(
            'Data',
            'Imie i nazwisko',
            'Adres',
            'Region',
            'Adres Email',
            'Nr Telefonu',
        );

        $column_headers = array_map('utf8_encode', $column_headers);

        fputcsv($csv_file, $column_headers, $delimiter);

        foreach ($results as $row) {
            $data_to_export = array(
                $row['id'],
                $row['imie'] . ' ' . $row['nazwisko'],
                $row['nazwa_salonu'] . ', ' . $row['ulica'] . ', ' . $row['kod_pocztowy'] . ' ' . $row['miasto'],
                $row['wojewodztwo'],
                $row['email'],
                $row['numer_telefonu'],
            );

            $data_to_export = array_map(function($item) use ($delimiter) {
                return str_replace(',', $delimiter, $item);
            }, $data_to_export);

            $data_to_export = array_map(function($item) {
                return mb_convert_encoding($item, 'UTF-8', 'auto');
            }, $data_to_export);
			
            $line = implode($delimiter, $data_to_export);
            fputs($csv_file, $line . "\n");
        }

        fclose($csv_file);

		$wpdb->flush();

        exit;
    }
}
Leave a Comment