Grunion_Contact_Form_Plugin::download_feedback_as_csv PHP Method

download_feedback_as_csv() public method

download as a csv a contact form or all of them in a csv file
    function download_feedback_as_csv()
    {
        if (empty($_POST['feedback_export_nonce'])) {
            return;
        }
        check_admin_referer('feedback_export', 'feedback_export_nonce');
        if (!current_user_can('export')) {
            return;
        }
        $args = array('posts_per_page' => -1, 'post_type' => 'feedback', 'post_status' => 'publish', 'order' => 'ASC', 'fields' => 'ids', 'suppress_filters' => false);
        $filename = date("Y-m-d") . '-feedback-export.csv';
        // Check if we want to download all the feedbacks or just a certain contact form
        if (!empty($_POST['post']) && $_POST['post'] !== 'all') {
            $args['post_parent'] = (int) $_POST['post'];
            $filename = date("Y-m-d") . '-' . str_replace(' ', '-', get_the_title((int) $_POST['post'])) . '.csv';
        }
        $feedbacks = get_posts($args);
        if (empty($feedbacks)) {
            return;
        }
        $filename = sanitize_file_name($filename);
        /**
         * Prepare data for export.
         */
        $data = $this->get_export_data_for_posts($feedbacks);
        /**
         * If `$data` is empty, there's nothing we can do below.
         */
        if (!is_array($data) || empty($data)) {
            return;
        }
        /**
         * Extract field names from `$data` for later use.
         */
        $fields = array_keys($data);
        /**
         * Count how many rows will be exported.
         */
        $row_count = count(reset($data));
        // Forces the download of the CSV instead of echoing
        header('Content-Disposition: attachment; filename=' . $filename);
        header('Pragma: no-cache');
        header('Expires: 0');
        header('Content-Type: text/csv; charset=utf-8');
        $output = fopen('php://output', 'w');
        /**
         * Print CSV headers
         */
        fputcsv($output, $fields);
        /**
         * Print rows to the output.
         */
        for ($i = 0; $i < $row_count; $i++) {
            $current_row = array();
            /**
             * Put all the fields in `$current_row` array.
             */
            foreach ($fields as $single_field_name) {
                $current_row[] = $this->esc_csv($data[$single_field_name][$i]);
            }
            /**
             * Output the complete CSV row
             */
            fputcsv($output, $current_row);
        }
        fclose($output);
    }